Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you cast an object to a long in c#?

I am pulling a 'long' value from Session, using a generic property, and it is crashing.

so I have:

public static T Get<T>(string key)
{
    if(...)
        return (T)System.Web.HttpContext.Current.Session[key];

    ...
}

When debugging, the value is 4, and it crashes.

like image 294
Blankman Avatar asked Dec 03 '22 12:12

Blankman


1 Answers

If you insist on keeping your generic method, you can use Convert.ChangeType():

public static T Get<T>(string key)
{
    if (...)
        return 
          (T) Convert.ChangeType(System.Web.HttpContext.Current.Session[key],
                                 typeof(T));

    ...
}

That will allow you to call:

long n = Get<long>("sessionkey");

But be careful: Convert.ChangeType() doesn't work for all conversions.

like image 141
Philippe Leybaert Avatar answered Dec 06 '22 00:12

Philippe Leybaert