Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are C# enums typesafe?

Tags:

c#

enums

Are C# enums typesafe?

If not what are the implications?

like image 352
Willbill Avatar asked Oct 16 '08 12:10

Willbill


1 Answers

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);

like image 58
Marc Gravell Avatar answered Oct 06 '22 01:10

Marc Gravell