Moving Beyond Enumerations
page 4 of 5
by Steven Smith
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 30322/ 49

Replacing Enums with Classes

Eventually, you need to upgrade from enums to classes in order to encapsulate both their state and behavior, if their behavior expands beyond mere named constants.  The best way to achieve this without breaking the enum use pattern is through the use of static classes.  When done properly, this refactoring can be done with little or no changes required in existing code that previously used the enum.  Consider the following Role class that can be used everywhere our existing enum was used in the previous examples:

In Visual Studio, when you type in "Role." you will get the following Intellisense:

Thus, the behavior mirrors that of an enum, constraining the options available.  The friendly display value is easily displayed without the need for attributes or reflection, using this code:

The issue with passing in values that are outside the range of the enumeration disappears as well.  The only way one could do such a thing would be through the use of reflection to remove the sealed marker on Role and create a subtype.  Otherwise, whether an invalid value is cast or an uninitialized value is passed into a method expecting a Role, an exception will result (you may wish to do your own null check).  These two tests both pass now:

The new implementation of RoleCanDoSomething() is simply:

And of course, now that Role is an actual class, some of these utility methods that were in EnumHelper or RoleHelper classes can be rolled into the Role class itself, if appropriate.

View Entire Article

User Comments

Title: Good Catch   
Name: Steve Smith
Date: 2011-08-30 7:56:15 PM
Good catch. Yes, those fields should be readonly, of course.

Title: public static roles should be readonly   
Name: Ian Mercer
Date: 2011-08-30 5:01:05 PM
Totally agree that enums should be replaced with classes as soon as they stop being enums. One improvement to your class would be to make all the values readonly, e.g.

public static readonly Author ...

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2024  |  Page Processed at 2024-06-23 9:30:30 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search