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

What should the default value be for my enum?

The prob­lem with default value is that enum is really an int under­neath, and as do all inte­gers in C# an enum has a default value of 0 when first cre­ated. So if 0 is not mapped to an enu­mer­a­tion con­stant then your enum will be instan­ti­ated 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­tively, if you don’t spec­ify 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­ated with the first value in the list. Again, there’s the prob­lem with the default value because most of the time there is no obvi­ous can­di­dates for the default value and it doesn’t make sense to just pick an arbi­trary enu­mer­a­tion to be the default value:

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 value 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 purposefully.

There­fore it’s always bet­ter to mark the default value 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
}
Share

2 Responses to “.Net Tips — marking the default enum value ‘Undefined’”

  1. […] .Net Tips — mark­ing the default enum value ‘Undefined … […]

  2. The plat­form was built from a scratch to over­come many of the prob­lems that com­monly accus­tomed with appli­ca­tion devel­op­ment i.e. time con­sum­ing devel­op­ment process.

Leave a Reply