Are C# enums typesafe?
If not what are the implications?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With