.Net Tips — marking the default enum value ‘Undefined’

enum is a tremen­dous­ly use­ful struc­ture in C#, but when defin­ing a new enum there is one thing you should always ask your­self:

What should the default val­ue be for my enum?

The prob­lem with default val­ue is that enum is real­ly an int under­neath, and as do all inte­gers in C# an enum has a default val­ue of 0 when first cre­at­ed. So if 0 is not mapped to an enu­mer­a­tion con­stant then your enum will be instan­ti­at­ed with an invalid valid:

public enum MyColour
{
    Red = 1,
    Green = 2,
    Blue = 3
}

MyColour colour = new MyColour(); // colour = 0, which is not a valid MyColour enumeration

Alter­na­tive­ly, if you don’t spec­i­fy the inte­ger val­ues for the enu­mer­a­tions the enu­mer­a­tion by default will start at 0, and a new enum will be instan­ti­at­ed with the first val­ue in the list. Again, there’s the prob­lem with the default val­ue because most of the time there is no obvi­ous can­di­dates for the default val­ue and it doesn’t make sense to just pick an arbi­trary enu­mer­a­tion to be the default val­ue:

public enum MyColour
{
    Red,    // 0
    Green, // 1
    Blue    // 2
}

MyColour colour = new MyColour(); // colour = MyColour.Red, but should a new colour default to red??

This can lead to sub­tle bugs, and are often hard to pick up on. Take for exam­ple a class that uses the MyColour enum, if the pro­gram­mer who wrote the class for­get to set the val­ue of the enum it’ll sim­ply read MyColour.Red, which is a valid case and with­out trac­ing through the code it’s dif­fi­cult to know whether the enum had been set to MyColour.Red pur­pose­ful­ly.

There­fore it’s always bet­ter to mark the default val­ue of an enum with some spe­cial enu­mer­a­tion such as None, or Unde­fined, etc.:

public enum MyColour
{
    Undefined = 0,
    Red = 1,
    Green = 2,
    Blue = 3
}