[Solved-4 Solutions] C# nullable string error



Error Description:

    private string? typeOfContract
    {
      get { return (string?)ViewState["typeOfContract"]; }
      set { ViewState["typeOfContract"] = value; }
    }
    
    click below button to copy the code. By - C# tutorial - team
    • Later in the code we use it like this:
    typeOfContract = Request.QueryString["type"];
    
    click below button to copy the code. By - C# tutorial - team
    • We get the following error at the declaration of typeOfContract line stating:
    • The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable<T>'

    Solution 1:

      • System.String is a reference type and already "nullable".
      • Nullable<T> and the ? suffix are for value types such as Int32, Double, DateTime, etc.

      Solution 2:

        • You are making it complicated. string is already nullable. You don't need to make it morenullable. Take out the ? on the property type.

        Solution 3:

          • string cannot be the parameter to Nullable because string is not a value type. String is a reference type.
          string s = null; 
          
          click below button to copy the code. By - C# tutorial - team
          • is a very valid statement and there is not need to make it nullable.
          private string typeOfContract
              {
                get { return ViewState["typeOfContract"] as string; }
                set { ViewState["typeOfContract"] = value; }
              }
          
          click below button to copy the code. By - C# tutorial - team

          Solution 4:

            • For nullable, use ? with all of the C# primitives, except for string.

            Related Searches to C# nullable string error