05 May 2016
C# – how to iterate through an enum
Posted in Computing, Programming By FraserG On May 5, 2016Frequently I find I wish to iterate through an enum type to add items to a list or do something with each item. Doing so is simple, but remembering how causes a good few minutes of Google searching, so this post is here as an aid to my memory the next time I wish to iterate over an enum.
To iterate over an enum, we simply need to get hold of the values the enum contains, which is done by using the method ‘GetValues’ associated with the Enum class, like so.
public enum AnalyserType { Analyser1, Analyser2, Analyser3, } private void LoopEnums() { foreach(AnalyserType a in Enum.GetValues(typeof(AnalyserType))) { DoSomething(a); } }
That’s all there is to it. Like I said, a nice, short, simple post to aid iterating through C# enums in the future.
About Author
FraserG
Computer Scientist currently undertaking an Engineering Doctorate degree discussing computing, programming, research and racing.