135
private string? typeOfContract
{
  get { return (string?)ViewState["typeOfContract"]; }
  set { ViewState["typeOfContract"] = value; }
}

Later in the code I use it like this:

typeOfContract = Request.QueryString["type"];

I am getting 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>'

Any ideas? Basically, I want to make sure that "type" exists in the QueryString before performing an action.

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Mike Fielden
  • 10,055
  • 14
  • 59
  • 99

5 Answers5

303

System.String is a reference type and already "nullable".

Nullable<T> and the ? suffix are for value types such as Int32, Double, DateTime, etc.

Joe
  • 122,218
  • 32
  • 205
  • 338
  • 13
    One thing to note: Nullable is a value type itself, but the "struct" generic type constraint only includes non-nullable value types - so you can't do Nullable>. – Jon Skeet Oct 09 '08 at 14:18
  • In C# 8.0 reference types may be marked as nullable. One may type `string?` to tell the world this string may be null. Ref: https://www.youtube.com/watch?v=VdC0aoa7ung – nkalfov Mar 04 '19 at 23:06
38

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

jop
  • 82,837
  • 10
  • 55
  • 52
19

string cannot be the parameter to Nullable because string is not a value type. String is a reference type.

string s = null; 

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; }
    }

should work because of the as keyword.

Szymon Rozga
  • 17,971
  • 7
  • 53
  • 66
13

String is a reference type, so you don't need to (and cannot) use Nullable<T> here. Just declare typeOfContract as string and simply check for null after getting it from the query string. Or use String.IsNullOrEmpty if you want to handle empty string values the same as null.

csgero
  • 2,753
  • 17
  • 15
4

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

The following page gives a list of the C# primitives: http://msdn.microsoft.com/en-us/library/aa711900(v=vs.71).aspx

g t
  • 7,287
  • 7
  • 50
  • 85
James Oravec
  • 19,579
  • 27
  • 94
  • 160