What is the proper way to check for null values?
What about
string y = (Session["key"] ?? "none").ToString();
You could also use as
, which yields null
if the conversion fails:
Session["key"] as string ?? "none"
This would return "none"
even if someone stuffed an int
in Session["key"]
.
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");