CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Darrell Norton's Blog [MVP]

Fill in description here...

The Benefits of Assigning a Non-default Value to Enums

As part of our current application, we are often using enums for the various benefits they bring.  One problem I ran into, though, is not assigning a non-zero (for integer enums) default value to the enum.

 

Why would this be a problem?  Well, when I want to use Debug.Assert to check the preconditions on my method!  For example, I have a property whose value is an enum and the precondition is that this property has been set (a value assigned to it).  If the default value of the enum is zero, any time I check to see if the property has been assigned to, it always passes since integers without values assigned to them default to zero.  And zero is the default value of your first constant unless you override it.

 

For my purposes, I have found it useful to start numbering the values of an integer enum at one instead of zero.  That way I can write (in VB):

 

Debug.Assert((Me.PricingSize = PricingSizeEnum.FirstChoice) Or (Me.PricingSize = PricingSizeEnum.SecondChoice) Or (Me.PricingSize = PricingSizeEnum.ThirdChoice), "PricingSize must be defined before calling this method")

 

This also works (which is more intuitive but may not be exactly correct, can anyone help explain if this is ok?): 

 

Debug.Assert(Me.PricingSize <> Nothing, "PricingSize must be defined before calling this method")



Check out Devlicio.us!