How can you enumerate an enum
in C#?
E.g. the following code does not compile:
public enum Suit
{
Spades,
Hearts,
Clubs,
Diamonds
}
public void EnumerateAllSuitsDemoMethod()
{
foreach (Suit suit in Suit)
{
DoSomething(suit);
}
}
And gives the following compile-time error:
'Suit' is a 'type' but is used like a 'variable'
It fails on the Suit
keyword, the second one.
If you need speed and type checking at build and run time, this helper method is better than using LINQ to cast each element:
And you can use it like below:
Of course you can return
IEnumerable<T>
, but that buys you nothing here.What if you know the type will be an
enum
, but you don't know what the exact type is at compile time?The method
getListOfEnum
uses reflection to take any enum type and returns anIEnumerable
of all enum values.Usage:
Some versions of the .NET framework do not support
Enum.GetValues
. Here's a good workaround from Ideas 2.0: Enum.GetValues in Compact Framework:As with any code that involves reflection, you should take steps to ensure it runs only once and results are cached.
Why is no one using
Cast<T>
?There you go
IEnumerable<Suit>
.Just to add my solution, which works in compact framework (3.5) and supports type checking at compile time:
- If anyone knows how to get rid of the
T valueType = new T()
, I'd be happy to see a solution.A call would look like this:
What the hell I'll throw my two pence in, just by combining the top answers I through together a very simple extension
Clean simple and by @Jeppe-Stig-Nielsen s comment fast.