Jul 13 2009

Make your types have 0 as a valid value

Category: C#,Software DevelopmentWil @ 8:07 am

Take the following simple code snippet:

internal enum MaritalStatus : byte
{
   Single = 1,
   Married = 2,
   Divorced = 3,
   Widowed = 5
}

class Program
{
   static void Main()
   {
      var maritalStatus = new MaritalStatus();
      Console.WriteLine("MaritalStatus value = " + maritalStatus);
   }
}

What is printed?  Well, 0 (zero) is printed.  That is because the .NET framework ensures that all new instances of objects get initialized to zero.

But MaritalStatus does not have a state for the value 0.  This is bad and is not what you expected.  Therefore, the solution is to “Always make your types have 0 as a valid state or value”.

If you have a business constraint where you are forced to supply the values to an enumeration like I did above, you have a problem.  But if that is not the case, you can do a couple of different things.  One, you can just leave off the numbers from the enum members entirely.  The top-most member will be set to zero; the next to one; the next to two… and so on.  The other option is to make a value that is zero.  Let’s redefine our MaritalStatus enum:

internal enum MaritalStatus : byte
{
   Undisclosed = 0,
   Single = 1,
   Married = 2,
   Divorced = 3,
   Widowed = 5
}

Now, MaritalStatus will always be “initialized” to ‘Undisclosed’ when created using the ‘new’ operator.

Of course, that also begs the question, “Why the hell are you creating an enum variable using the ‘new’ operator”.  Hey, I’m not judging.  It’s your source code.  Do whatever you like.  The software gods would smile down on you more often if you create your enums this way instead:

var maritalStatus = MaritalStatus.Married;

One Response to “Make your types have 0 as a valid value”

  1. Casey says:

    Excellent point! I usually make 0 = UNDEFINED for all enumerations. Not only does it get you around the default value quirk that you’re talking about but it also lets you provide a default value for your enumeration without having to use nullable value types.

Leave a Reply

Spam Protection by WP-SpamFree Plugin

Get Adobe Flash playerPlugin by wpburn.com wordpress themes