The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Email Subscription

    Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 716 other subscribers

.NET/C# – an easier foreach for enums using generic methods

Posted by jpluimers on 2009/04/28

I like enums. Maybe because of my Turbo Pascal and Delphi background. They are descriptive. Makes code easier to read.

[sourcecode language=’csharp’]
public enum TrafficLightColors
{
Red,
Yellow,
Green
}
[/sourcecode]

But using them in C# foreach loops is a bit of a pain, not so much in the loop itself, but more in getting the list of values to loop over.

The Delphi equivalent would be like this, including a loop to run through all of the enumeration values (note that in Delphi, it us good practice to start types with a T):

[sourcecode language=’delphi’]
type
TTrafficLightColors = (Red, Yellow, Green);
var
TrafficLightColor: TTrafficLightColors;
begin
for TrafficLightColor := Low(TTrafficLightColors) to High(TTrafficLightColors) do
// some business logic
end;
[/sourcecode]

Quite a while ago, I was fed up writing code to get the list of values like below; it felt much to awkward, and way too many occasions of the TrafficLightColors type, so this is an excellent candidate to simplify using use C# Generics.

[sourcecode language=’csharp’]
Array values = Enum.GetValues(typeof(TrafficLightColors));
TrafficLightColors[] colorsArray = (TrafficLightColors[])values;
foreach (TrafficLightColors color in colorsArray)
Console.WriteLine(color);
[/sourcecode]

I’d much rather write code like this using the TrafficLightColors type much less:

[sourcecode language=’csharp’]
TrafficLightColors[] colorsArray = EnumHelper.EnumToArray();
foreach (TrafficLightColors color in colorsArray)
Console.WriteLine(color);

List colorsList = EnumHelper.EnumToList();
foreach (TrafficLightColors color in colorsList)
Console.WriteLine(color);
[/sourcecode]

In fact, I’d even hoped that extension methods would eliminate the use of the reference to EnumHelper but explaining that will be part of a future blog.

So lets end with the tiny EnumHelper class:

[sourcecode language=’csharp’]
using System;
using System.Collections.Generic;

namespace bo.Generic
{
public class EnumHelper
{
public static T[] EnumToArray()
{
Array values = Enum.GetValues(typeof(T));
T[] result = (T[])values;
return result;
}

public static List EnumToList()
{
T[] array = EnumToArray();
List result = new List(array);
return result;
}
}
}
[/sourcecode]

That should get you going simplifying your enum based foreach loops.

–jeroen

Leave a Comment

 

Discover more from The Wiert Corner - irregular stream of stuff

Subscribe now to keep reading and get access to the full archive.

Continue reading