Type-safe Enumeration of Enum Values in C#

The seem to be (at least!) 3 way to enumerate all defined values of an enum definition. The simplest uses Enum.GetValues(), but returns an array whose values need to be cast to the specific enum:

var values = Enum.GetValues(typeof (MyEnum));
foreach (MyEnum v in values) { }

.Net 3.5 and Linq introduced the Cast<>() extension method which allows a type-safe cast of each member of the array to be cast to the enum:

var values = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>();

Still, the enum type needs to be specified twice.

More sophisticated, the UnconstrainedMelody library directly defines a type-safe enumeration of enum values like this:

var values = Enums.GetValues<MyEnum>();

Time to clean up your code if your project contains two or more ways to iterate through enum values… šŸ˜‰

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: