Consider the following code
enum HorizontalAlignment { Left, Middle, Right };
enum VerticleAlignment { Top, Middle, Bottom };
function OutputEnumValues (Type enumType)
{
foreach (string name in Enum.GetNames(typeof(enumType)))
{
Console.WriteLine(name);
}
}
Which can be called like
OutputEnumValues (typeof(HorizontalAlignment));
OutputEnumValues (typeof(VerticleAlignment ));
But I could inadvertantly call, for example
OutputEnumValues (typeof(int));
And this will compile but fail at runtime at Enum.GetNames()
Any way of writing the method signature to catch this sort of problem at compile time – i.e. only accepting enum types in OutputEnumValues?
Every enum type is just an integer (which can be 8-, 16-, 32- or 64-bit and signed or unsigned). You can cast the integer
0to any enum type, and it will become a value that is statically typed to the enum.Furthermore, you can have a parameter of type
Enumto ensure that only enum values are passed in, without knowing the actual enum type.Thus, my solution looks like this:
and then:
This works for all enum types no matter their underlying integer type.