I was testing a bit of code I wrote and was wondering if a default case handling was needed.
Lets define MyEnum like this
public enum MyEnum
{
[Description("Value")]
Value = 0,
[Description("Other value")]
OtherValue = 1,
}
the logic I was asking myself about was similar to this one :
MyEnum val = (MyEnum)8;
if(val == MyEnum.Value)
//do stuff
else if (val == MyEnum.OtherValue)
//do other stuff
else
throw new ArgumentException("The value is not currently supported");
My reasoning was to not have a default case because the cast from a value not defined in the Enum would throw an exception anyway before even being caught by my piece of code.
So I tryed with the exemple I have up here and at my suprise the cast didn't threw any exception and it was my default case handling witch threw the exception.
My question is : Why is the cast of any int to MyEnum is valid? I understand that in this exemple the underlying value of the Enum is int but I would have expected an exception to been thrown from the cast. Why is that Valid?
if...else, useswitch. Also, there is a dedicated exception type for that kind of situations that should be thrown here, namelyInvalidEnumArgumentException.InvalidEnumArgumentExceptionbut about the switch I personnaly don't really like it when it come to test only a couple of value (here in my real code I'm actually testing only 3 value)