Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method parameter with strongly typed Enum type

Tags:

c#

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?

like image 850
Ryan Avatar asked May 01 '26 05:05

Ryan


1 Answers

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.

like image 101
Timwi Avatar answered May 03 '26 18:05

Timwi