You can add a *little* bit of behavior to enums through the
use of attributes and reflection. One common approach to the problem of
displaying enums in a user-friendly manner is to add an attribute that can be
used for display purposes. You can create your own attribute, but it's
probably better to use one that already exists and is well-suited to this
purpose, such as the System.ComponentModel.Description attribute. You can add
it to any or all of your enumeration values in order to specify the
"friendly" name that you want to display in your application. The
Role enum would then look like this (note the addition of a few more roles that
I'll get to in a moment):
Now we can create a new method to help use fetch the
description of a given enum. This one is borrowed from this
If we adjust our method for displaying the enumerations,
we'll now get "Sales Representative" output as we wanted.
You can of course continue down this road for as long as you
wish, but personally I draw the line with one attribute. If your enumeration's
items each require 2 or more attributes, I would argue that you have stepped
beyond capabilities of the enum type, and that you should upgrade to a class.
The additional behavior required of enums can come in many forms, but one I've
seen frequently relates to visibility of options to end users.
As you saw above, there are now two Secret roles that should
not be displayed with the other roles. Not only that, but additional roles are
also planned, some of which will be visible and some not (such as the new
Manager role, which should be visible). Our initial test of the new
requirement that Secret roles not be displayed fails:
We could fix it in the DisplayFriendlyNames() method by
adding individual checks for each role, but this gets ugly quickly. Better
would be if there were some kind of IsVisible property on the enum. We could
again turn to attributes, and perhaps create a [Visible(false)] or similar for
the purpose, but as I noted, I draw the line with one attribute.