Validating Enum Values

Question
Should non-bit-coded enum values be validated when passed to properties or methods as arguments?

Answer
Yes, always validate these values.

Comments
Why? Using an enum parameter only guarantees the value being passed in is an integer. It doesn’t guarantee the value is one of the constants defined in the enum, and it’s possible to define invalid enum values. For example:

DayOfTheWeek dayOfWeek = (DayOfTheWeek) 100;

Example
Here’s an example of how to properly implement a property that takes and returns enum members with no invalid values.

private DayOfTheWeek weekDay = DayOfTheWeek.Sunday;

public DayOfTheWeek WeekDay {
    get {
        return weekDay;
    }
    set {
        if ( value < DayOfTheWeek. Sunday || value > DayOfTheWeek.Saturday ) {
            throw new ArgumentException("Invalid day of the week.");
        weekDay = value;
        }
    }
}

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s