Nolonar Nolonar - 2 months ago 12
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

of enum values. The code I normally use looks like this:


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
I'd need to write
, which is quite confusing and not very pretty either.

Which leads me to this question: Is there a better way to get an
of enum values than using

Do I really have no other choice but to make it

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


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.