What is the proper way to check for null values?
What about
string y = (Session["key"] ?? "none").ToString();
If you're frequently doing this specifically with ToString()
then you could write an extension method:
public static string NullPreservingToString(this object input)
{
return input == null ? null : input.ToString();
}
...
string y = Session["key"].NullPreservingToString() ?? "none";
Or a method taking a default, of course:
public static string ToStringOrDefault(this object input, string defaultValue)
{
return input == null ? defaultValue : input.ToString();
}
...
string y = Session["key"].ToStringOrDefault("none");