Defensive Programming – Verifying Enum Values

One thing I see programmers overlook all the time in their coding is that a valid enumeration value was passed into a method or property. For example, I did an analysis on a 30 project solution that has over 83K lines of code and only once was the enum value verified!

As I tell programmers all the time “All data is bad until you verify it!”. When using an enumeration in .NET, the default type is an INT32. The means that if you specify in your code enum values of 0 – 5, this does not prevent code from sending in any valid INT32 value! If a value of lets say 6 is sent via a parameter, your code will break!

The simplest way of checking for a valid enum value is to use the IsDefined method off of the enum type. Here is an example:

public Environment .SpecialFolder RootFolder
{
    get
    {
        return this ._rootFolder;
    }
    set
    {
        if (!Enum .IsDefined(typeof (Environment .SpecialFolder ), value ))
        {
            throw new InvalidEnumArgumentException ("value" , (int )value , 
 typeof (Environment .SpecialFolder ));
        }
        this ._rootFolder = value ;
    }
}

One thought on “Defensive Programming – Verifying Enum Values

Comments are closed.