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 717 other subscribers

Archive for November 30th, 2011

Duh moment: in C#, the integer zero (0) is compatible with all enums

Posted by jpluimers on 2011/11/30

Even if you have used something for over a decade, you can learn about it :)

I was refactoring bits of code where someone clearly didn’t understand the benefits of enumerations, similar to this very contrived example:

[sourcecode language=”csharp”]
using System;

namespace Demo
{
// explicit equivalence of:
// public enum TrafficLight { Red, Yellow, Green };
public enum TrafficLight { Red = 0, Yellow = 1, Green = 2 };

public class Program
{
public static void Main()
{
// old code:
Console.WriteLine(IntIsRedTrafficLight((int)TrafficLight.Red));
Console.WriteLine(IntIsRedTrafficLight((int)TrafficLight.Yellow));
Console.WriteLine(IntIsRedTrafficLight((int)TrafficLight.Green));
}

public static bool IntIsRedTrafficLight(int trafficLight)
{
return (trafficLight == (int)TrafficLight.Red);
}
}
}
[/sourcecode]

The code was using way too many casts, and my goal was something as simple as this: Read the rest of this entry »

Posted in .NET, C#, Development, Software Development | Leave a Comment »