As everyone else has said, string
doesn't need ?
(which is a shortcut for Nullable<string>
) because all reference types (class
es) are already nullable. It only applies to value type (struct
s).
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();
}