Enumerations are one of many useful tools at the fingertips
of developers. Most of us have been using them for years. Because they are so
common and easy to use, I believe we sometimes overuse them. An enumeration at
its core is merely a number value. Try this in C# and you will see how easy it
is to convert between enumerations and integer values. Enumerations are useful
because they are named collections of values which are associated under the
surface with integer values.
This example shows how one could quickly and easily print
out the names and number values of an enumeration.
Listing 1: Simple Enumeration Console Output
using System;
class Program
{
static void Main(string[] args)
{
HaveFunWithEnums();
}
public static void HaveFunWithEnums()
{
Console.WriteLine(MyEnum.Something);
Console.WriteLine(MyEnum.SomethingElse);
Console.WriteLine(MyEnum.AndNow);
Console.WriteLine(MyEnum.ForSomething);
Console.WriteLine(MyEnum.CompletelyDifferent);
Console.WriteLine((int)MyEnum.Something);
Console.WriteLine((int)MyEnum.SomethingElse);
Console.WriteLine((int)MyEnum.AndNow);
Console.WriteLine((int)MyEnum.ForSomething);
Console.WriteLine((int)MyEnum.CompletelyDifferent);
}
}
internal enum MyEnum
{
Something,
SomethingElse,
AndNow,
ForSomething,
CompletelyDifferent
}
That is some very easy code, and I think most people have
probably seen enumerations printed by name as well enums converted to integers
and their values used. So if enums are so great, why would I write an article
talking about a way of avoiding them? Well, I would first like to say that I am
a big fan of enums. I think they are quite useful; they just have some risks as
well as some circumstances under which they fall a little bit short as far as
software design is concerned.