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,
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;