1

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
}

2 Answers 2

3

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I guess I should have RTFM :)
2

From MSDN Enum.ToObject Method (Type, Int32)

The ToObject(Type, Int32) method converts value to an enumeration member whose underlying value is value. Note that the conversion succeeds even if value is outside the bounds of enumType members. To ensure that value is a valid underlying value of the enumType enumeration, pass it to the IsDefined method.

So it is by design.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.