views:

218

answers:

3

Follow along in my test source. What is a good way to get a value from a enum object? Must support long. I am attempting without a try/catch block.

enum ELong: long { a = 0x100000000 };
enum ENormal { a = 25 }

        var l = (object) ELong.a;
        var n = (object)ENormal.a;
        //will cast into the correct size
        int ii = (int)n; //ok
        long ll = (long)l; //ok
        //wont cast if its too big
        ll = (long)n; //cast exception
        //or too small
        n = (int)l; //cast exception//compile error. Cannot cast
        //lets try preventing the exception with is
        if (n is int)
            ii = (int)n;//doesnt get here.
        if (n is long)
            ll = (long)n;//doesnt get here.
        if (l is int)
            ii = (int)l;//doesnt get here
        if (l is long)
            ll = (long)l;//doesnt get here
        //WHY!!!!
        //Maybe as will do the trick?
        if (n as int? != null)
            ii = (int)n;//doesnt get here.
        if (n as long? != null)
            ll = (long)n;//doesnt get here.
        if (l as int? != null)
            ii = (int)l;//doesnt get here
        if (l as long? != null)
            ll = (long)l;//doesnt get here
        //geez. What is more stange is (int) will work while (int?) will not
        int? ni = (int?)n;//cast exception
        int iii = (int)n; //works
        ll = (long)n;
+4  A: 
long test1 = Convert.ToInt64(l); // 4294967296
long test2 = Convert.ToInt64(n); // 25
Marc Gravell
Convert.ToInt64 will throw exception. What about Int64.TryParse method
Adeel
argh, i wonder what the convert class does behind the scenes. Hopefully not a normal cast inside a try block. But that would make sense. -edit- ThinkJet answered it. I can guess what ChangeType may do.
acidzombie24
Adeel: I tried it, it works fine as long as it is a enum. I would want an exception if i somehow allowed the object to not be an enum or Value type.
acidzombie24
+3  A: 

Explanation

if (n is int)
        ii = (int)n;//doesnt get here.
    if (n is long)
        ll = (long)n;//doesnt get here.
    if (l is int)
        ii = (int)l;//doesnt get here
    if (l is long)
        ll = (long)l;//doesnt get here

n and l is neither int/long nor long?/int?, the are of type of you enum, so this is expected behavior.

Solution

Probably you should use Convert class to achieve what you want.

Restuta
+2  A: 

Example from MSDN:

static object GetAsUnderlyingType(Enum enval)
{
    Type entype = enval.GetType();

    Type undertype = Enum.GetUnderlyingType(entype);

    return Convert.ChangeType( enval, undertype );
}
  1. Convert to underlying type (int or long)
  2. Cast converted value to your variable (I guess simple assign result to long variable).
ThinkJet
It's gonna be pretty slow, but that is what I am using as well. (If I can't help myself otherwise)
Robert Giesecke
Great answer as well!
acidzombie24