Search code examples
c#.netcastingenumslinqpad

Casting to invalid enum value, Enum.ToObject, does not throw exception, sets Enum to int


Is this normal behavior?

Writing an enum casting for

1) Try text parsing 2) Fallback to int parsing.

int parsing never throws an error...

Try running the following script in LinqPad, I haven't tested other compilers than linqpad, but I doubt it's an Linqpad issue.

How can I throw an error if int matching fails ?

void Main()
{
    FieldAttributes fieldattributeenum = FieldAttributes.Assembly;
    B b = B.Valx1;      
    b.Dump("B = "+((int)b).ToString()); //Valx1 (11);

    fieldattributeenum.Dump("fieldattributeenum = " +((int)fieldattributeenum).ToString()); //Assembly (3)

    b = (B) Enum.ToObject(typeof(B), (int) fieldattributeenum); 
    b.Dump("B = "+((int)b).ToString()); //valcorrect3 (3)
    A a = (A) Enum.ToObject(typeof(A), (int) fieldattributeenum); //
    a.Dump("A = "+ ((int)a).ToString()); // ??? (3) 
}

public enum B{  
    Valx1=11,
    Valx2=12,
    Valx3=13,
    Valx4=14,
    valcorrect3 = 3
}
public enum A{  
    Valx1=11,
    Valx2=12,
    Valx3=13,
    Valx4=14,
    valcorrect3
}

Solution

  • Just use Enum.IsDefined. Basically enums are just ints and you can assign any int to an enum even if it isn't defined.

    if(!Enum.IsDefined(typeof(A), a))
    {
        throw new InvalidCastException("Not a valid value for A: " + a);
    }