If it walks like a class, talks like a class, it probably is a class

I occasionally come across attempts to extend Enums to include additional fields. These attempts typically use Attributes and reflection to get at the extra values. I have to say I don’t like them. The most extreme example of trying to get an Enum to do something else was this article on Code Project attempting to create a new type of enum: http://www.codeproject.com/KB/cs/EnumBuilder.aspx. Eugh!

Why do folks get so obsessed with trying to make enums do things that classes do better?

  • As soon as you hit a limitation that an Enum can’t handle your best bet is to create a class.
  • Need inheritance => use classes
  • Need more than one value on the object => use a class
  • Need more control over ToString() => use a class
  • Need to be able to localize the string value => use a class
  • Might need to do any of these in the future => use a class
  • If in doubt => use a class

If you do this your code will be

  1. more readable: you can say “x is Duck” instead of “x == Animal.Duck”
  2. more maintainable
  3. more extensible
  4. more object oriented (less switch statements and branching code)
  5. easier to localize (if you use the Enum’s name in the UI which isn’t a good practice anyway)
  6. almost certainly more efficient than using enums and reflection


Mon Feb 01 2010 05:49:31 GMT-0800 (Pacific Standard Time)


Next page: Looking forward to the new year and our new datacenter

Previous page: MongoDB substring search with a difference


Disqus goes here