After getting let down by a simple codeline like
char _letter = (char)Session["currentLetter"];
failing when the session is reset, I found out I wanted to try something. (currentLetter keeps track of position in a user table)
public static class SessionManager
{
public static T ValueOrDefault<T>(HttpSessionStateBase session, string sessionkey, T defaultvalue)
{
object item = session[sessionkey];
if (item != null && item.GetType() == typeof(T))
{
return (T)item;
}
else
{
return (T)defaultvalue;
}
}
}
Is this very wrong? Or am I doing something right here? (The code works, btw)
Some more comments:
Instead of
item.GetType() == typeof(T), you may have wanted to use:typeof(T).IsAssignableFrom(item.GetType()).This would let you support reading a type derived from
T.That said, in your specific case, if I understand the scenario correctly, I would have returned the default value only if the condition
item == nullis true.In your current code, the caller may get the default value returned if he was asking for the wrong type, which might be confusing for the caller as he has no way of knowing if a value was available or not.
I would risk an assumption that if a caller is trying to get a value using the wrong type, this is always due to a bug (and not for example due to invalid user input), and therefore I would prefer to have an
InvalidCastExceptionthrown on me, so that the bug can be fixed (instead of the bug being hidden by returning a default value).