How useful are enums?

I have been reviewing code and designs lately and when you have a discrete set of values that can be grouped together, you should use enumerations. Or does it really matter? Since .Net will allow you to pass in any integer value in place of an enumeration, you must still validate their values by either executing Enum.IsDefined() or some comparison operation (e.g. switch statement) to determine valid values. As Brad Abrams points out in this blog, IsDefined is expensive...and may not work as expected. So a switch statement is the only real way to validate valid values without a performance hit.

Now I still think Enum's are valuable, but you have to admit that they are far less useful when it comes to validation. Will it require that I come up with a Validating Attribute for my architecture as I do for validating other parameter types. For example:

public void UpdateBillingOption(
   [RequiredItem()][CustomerAccountNumber()]string accountNumber16,
   [RequiredItem()][MakeSureEnumIsValid(typeof(eBillingOption))] eBilling Option billingOption)

{
}
Will this really work?

Or should I use the converter concept and always use my custom converter classes to convert a value and throw a validation exception if it cannot make the conversion? For example:

eTaskCode taskCode = (eTaskCode)TypeDescriptor.GetConverter(typeof(

               eTaskCode)).ConvertFrom(eTaskCode.Task.ToString());

-Mathew Nolton

3 Comments

Comments have been disabled for this content.