sarsnake
sarsnake

Reputation: 27723

Returning nullable string types

So I have something like this

public string? SessionValue(string key)
{
    if (HttpContext.Current.Session[key].ToString() == null || HttpContext.Current.Session[key].ToString() == "")
        return null;

    return HttpContext.Current.Session[key].ToString();
}

which doesn't compile.

How do I return a nullable string type?

Upvotes: 18

Views: 24843

Answers (5)

Lucas
Lucas

Reputation: 17434

As everyone else has said, string doesn't need ? (which is a shortcut for Nullable<string>) because all reference types (classes) are already nullable. It only applies to value type (structs).

Apart from that, you should not call ToString() on the session value before you check if it is null (or you can get a NullReferenceException). Also, you shouldn't have to check the result of ToString() for null because it should never return null (if correctly implemented). And are you sure you want to return null if the session value is an empty string ("")?

This is equivalent to what you meant to write:

public string SessionValue(string key)
{
    if (HttpContext.Current.Session[key] == null)
        return null;

    string result = HttpContext.Current.Session[key].ToString();
    return (result == "") ? null : result;
}

Although I would write it like this (return empty string if that's what the session value contains):

public string SessionValue(string key)
{
    object value = HttpContext.Current.Session[key];
    return (value == null) ? null : value.ToString();
}

Upvotes: 7

Steef
Steef

Reputation: 34685

string is already nullable on its own.

Upvotes: 0

Jeff Meatball Yang
Jeff Meatball Yang

Reputation: 39057

String is already a nullable type. You don't need the '?'.

Error 18 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'

Upvotes: 0

Brandon
Brandon

Reputation: 70022

You can assign null to a string since its a reference type, you don't need to be able to make it nullable.

Upvotes: 0

Andy White
Andy White

Reputation: 88415

String is already a nullable type. Nullable can only be used on ValueTypes. String is a reference type.

Just get rid of the "?" and you should be good to go!

Upvotes: 42

Related Questions