I have this existing code which works very well.
public static T SessionGet<T>(string key)
{
if (Session[key] == null)
return default(T);
else
return (T)Session[key];
}
I wanted to make a version that works for Request. I realise that Request is string based. So how can I change the code so that error, as in the comment below, does not occur without having to place a large switch based on typeof(T).
return (T)Request[key]; // Cannot cast expression of type 'string' to type '(T)'
Here is the function….
public static T RequestGet<T>(string key)
{
if (Request[key] == null)
return default(T);
else
return (T)Request[key];
}
thank you
You can use the
Convert.ChangeTypemethod to accomplish this, but you’re relying on the inputs to be correct, otherwise you’ll get an exception.Requestdeals with user supplied data, so this assumption is extremely risky. This isn’t the same as what you’re doing withSession, as you control what goes intoSession. That’s not the case withRequest.In your shoes, I might want to rely on safer methods of getting, validating, and parsing user inputs so that the application doesn’t become a mess of exception handling or error screens.