If I have an enum like so:
enum Beer
{
Bud = 10,
Stella = 20,
Unknown
}
Why does it not throw an exception when casting an int that is outside of these values to a type of Beer?
For example the following code doesn’t throw an exception, it outputs ’50’ to the console:
int i = 50;
var b = (Beer) i;
Console.WriteLine(b.ToString());
I find this strange…can anyone clarify?
Taken from Confusion with parsing an Enum
This was a decision on the part of the people who created .NET. An enum is backed by another value type (
int,short,byte, etc), and so it can actually have any value that is valid for those value types.I personally am not a fan of the way this works, so I made a series of utility methods:
This way, I can say:
… or:
Edit
Beyond the explanation given above, you have to realize that the .NET version of Enum follows a more C-inspired pattern than a Java-inspired one. This makes it possible to have “Bit Flag” enums which can use binary patterns to determine whether a particular “flag” is active in an enum value. If you had to define every possible combination of flags (i.e.
MondayAndTuesday,MondayAndWednesdayAndThursday), these would be extremely tedious. So having the capacity to use undefined enum values can be really handy. It just requires a little extra work when you want a fail-fast behavior on enum types that don’t leverage these sorts of tricks.