Nolonar Nolonar - 1 month ago 8
C# Question

Is there a better way to enumerate an enum's values than Enum.GetValues()?

There are several situations where I want to have an

IEnumerable<MyEnum>
of enum values. The code I normally use looks like this:

Enum.GetValues(typeof(MyEnum)).OfType<MyEnum>()


But not only is it not very pretty to look at, most people will need a couple of seconds to understand what it does. It's also a huge pain to write, especially when you need it on multiple occasions throughout the code.

To make my life easier, I've decided to write an extension method like this:

public static IEnumerable<T> GetValues<T>(this T e) where T : Enum
{
return Enum.GetValues(typeof(T)).OfType<T>();
}


Except I have to get rid of the
where T : Enum
part, because "Constraint cannot be special class 'Enum'". Also, it's not exactly what I want, because instead of
MyEnum.GetValues()
I'd need to write
MyEnum.Value.GetValues()
, which is quite confusing and not very pretty either.

Which leads me to this question: Is there a better way to get an
IEnumerable<MyEnum>
of enum values than using
Enum.GetValues()
?

Do I really have no other choice but to make it
Helper.GetEnumValues<MyEnum>()
?

If possible, I'd like a solution that works in Unity, but any solution would be appreciated either way.

Answer

This is the perfect solution. .Net does not offer a strongly-typed Enum.GetValues at this time. People will only take a few seconds to understand what this does because one would expect .Net to offer a strongly-typed enumeration of Enums of one type right now.

You're using GetValues correctly as MSDN suggests.

Comments