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 ;
    }
}

Advertisements

One thought on “Defensive Programming – Verifying Enum Values

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s