I love the null-coalescing operator because it makes it easy to assign a default value for nullable types.
int y = x ?? -1;
That\'s great,
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");
My preference, for a one off, would be to use a safe cast to string in case the object stored with the key isn't one. Using ToString()
may not have the results you want.
var y = Session["key"] as string ?? "none";
As @Jon Skeet says, if you find yourself doing this a lot an extension method or, better, yet maybe an extension method in conjunction with a strongly typed SessionWrapper class. Even without the extension method, the strongly typed wrapper might be a good idea.
public class SessionWrapper
{
private HttpSessionBase Session { get; set; }
public SessionWrapper( HttpSessionBase session )
{
Session = session;
}
public SessionWrapper() : this( HttpContext.Current.Session ) { }
public string Key
{
get { return Session["key"] as string ?? "none";
}
public int MaxAllowed
{
get { return Session["maxAllowed"] as int? ?? 10 }
}
}
Used as
var session = new SessionWrapper(Session);
string key = session.Key;
int maxAllowed = session.maxAllowed;
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 it will always be a string
, you can cast:
string y = (string)Session["key"] ?? "none";
This has the advantage of complaining instead of hiding the mistake if someone stuffs an int
or something in Session["key"]
. ;)
create an auxiliary function
public static String GetValue( string key, string default )
{
if ( Session[ key ] == null ) { return default; }
return Session[ key ].toString();
}
string y = GetValue( 'key', 'none' );