Just use the zero-coalescing operator:
string value = (session["key"] ?? String.Empty).ToString();
Update
If you should have a way to do this (extension or other), I would do something like:
public static string GetValue(this HttpSessionState session, string key)
{
return (session[key] ?? String.Empty).ToString();
}
, GetValue
, , lambdas:
public static T GetValue<T>(this HttpSessionState session, string key, Func<object, T> valueSelector)
{
return valueSelector(session[key]);
}
public static string GetStringValue(this HttpSessionState session, string key)
{
return session.GetValue(key, x => (x ?? String.Empty).ToString());
}
:
string value = session.GetStringValue("key");