IT:AD:Patterns:Enums Start with Undefined Strategy
Summary
Process
Consider
public enum Gender{ Male =1, Female =2 }
Much as you don't want to admit it…zero's are a common source of bugs. So if your code somehow ends up setting a property to:
person.Gender= (Gender)0
You'll be surprised to know that it won't complain, even if 0 is not a member of the enum list.
The only way that you can Validate such a scenario is by doing something like the following.
public static void Validate(this Person person){ if ( ((int)person.Gender) == 0){throw ....} }
which of course nobody will do (as they'll be thinking about using the enum, not the unitituive int).
So just account for the use of a zero getting in there somehow. Put it at the beginning of the enum:
public enum Gender{ Undefined=0 Male =1, Female =2 }
Now you can test for it.
public static void Validate(this Person person){ if (person.Gender == Gender.Undefined){throw ....} }
While you're at it, you might as well consider whether there is such a case as Unknown. In which case, give it a value of 1:
public enum Gender{ Undefined=0, Unknown=1, Male =2, Female =3, }
Now it's clearer.