As shown in the example above, it is possible to pass a value outside of the range of an enum's allowed values. Due to this, it is advised that you validate all enum parameters. There are a number of ways to do this, with some techniques better than others. The following example shows three different methods.
C#:
public enum WeekDay
{
Sunday = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
}
public static class WeekDayHelper
{
public static bool IsWorkDay1(WeekDay day)
{
if (day < WeekDay.Sunday || day > WeekDay.Saturday)
throw new InvalidEnumArgumentException("day", (int)day, typeof(WeekDay));
return day >= WeekDay.Monday && day <= WeekDay.Friday;
}
public static bool IsWorkDay2(WeekDay day)
{
switch (day)
{
case WeekDay.Sunday:
case WeekDay.Saturday:
return false;
case WeekDay.Monday:
case WeekDay.Tuesday:
case WeekDay.Wednesday:
case WeekDay.Thursday:
case WeekDay.Friday:
return true;
}
throw new InvalidEnumArgumentException("day", (int)day, typeof(WeekDay));
}
// Not recommended
public static bool IsWorkDay3(WeekDay day)
{
if (!Enum.IsDefined(typeof(WeekDay), day))
throw new InvalidEnumArgumentException("day", (int)day, typeof(WeekDay));
return day >= WeekDay.Monday && day <= WeekDay.Friday;
}
}
In the first method, IsWorkDay1, the enum parameter is validated to ensure that it equal to or between the lowest valid value and the highest valid value. This has the benefit of being the cheapest, however, if during development of a product and the values of the enum changes, it could validate the values incorrectly.
The second method, IsWorkDay2, uses a switch statement to validate day. This doesn't suffer from the same problem as IsWorkDay1 (if the enum is in the same assembly) and it becomes an easy way to validate, if later in the method you are going to switch on the parameter anyway.
Although IsWorkDay3 is the simplest, it is the least recommended. Enum.IsDefined uses Reflection and rarely touched metadata to determine the valid values of the enum, and because of this, is very expensive in comparision to the other two techniques. It also suffers from a versioning issue, which is explained here: http://blogs.msdn.com/kcwalina/archive/2004/05/18/134208.aspx