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.