2

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

Valamas
  • 24,169
  • 25
  • 107
  • 177

1 Answers1

6

You can use the Convert.ChangeType method to accomplish this, but you're relying on the inputs to be correct, otherwise you'll get an exception. Request deals with user supplied data, so this assumption is extremely risky. This isn't the same as what you're doing with Session, as you control what goes into Session. That's not the case with Request.

public static T RequestGet<T>(string key)
{
    if (Request[key] == null)
    {
        return default(T);
    }
    else
    {
        return (T)Convert.ChangeType(Request[key], typeof(T));
        // return (T)Request[key];
    }
}

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.

Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246