Mike Fielden
Mike Fielden

Reputation: 10153

C# nullable string error

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.

Upvotes: 135

Views: 140741

Answers (5)

James Oravec
James Oravec

Reputation: 20391

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

Upvotes: 4

to StackOverflow
to StackOverflow

Reputation: 124696

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

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

Upvotes: 303

jop
jop

Reputation: 84043

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.

Upvotes: 38

csgero
csgero

Reputation: 2773

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.

Upvotes: 13

Szymon Rozga
Szymon Rozga

Reputation: 18168

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.

Upvotes: 19

Related Questions