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 0 to any enum type, and it will become a value that is statically typed to the enum.
Furthermore, you can have a parameter of type Enum to ensure that only enum values are passed in, without knowing the actual enum type.
Thus, my solution looks like this:
public static void OutputEnumValues(Enum example)
{
foreach (string name in Enum.GetNames(example.GetType()))
{
Console.WriteLine(name);
}
}
and then:
OutputEnumValues((HorizontalAlignment) 0);
OutputEnumValues((VerticalAlignment) 0);
This works for all enum types no matter their underlying integer type.
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