Are C# enums typesafe?

c#, enums

Solution

To give a slightly different answer... while the values are type-safe from the casting perspective, they are still unchecked once they have been cast - i.e.

enum Foo { A = 1, B = 2, C = 3 }    
static void Main()
{
    Foo foo = (Foo)500; // works fine
    Console.WriteLine(foo); // also fine - shows 500
}

For this reason, you should take care to check the values - for example with a `default` in a `switch` that throws an exception.

You can also check the (for non-`[Flags]` values) via:

bool isValid = Enum.IsDefined(typeof(Foo), foo);

Problem

Are C# enums typesafe? If not what are the implications?

Original source