Use Enum (C#) instead of magic numbers

May 29th, 2007 by Sameer | Filed under .NET articles.

Enumerations (enums) make your code much more readable and understandable.  If you are ever writing code that looks like

if (_mode == "5")

which I see time and time again, STOP!  It will be so difficult for future developers to understand what your code is supposed to do, and it will require you to add another line saying

// mode 5 is read only

However, if you did something nicer like,

if (_mode == Mode.Read)

You have automatically documented your code and made it easier to nderstand.  One way to reduce the amount of documentation that you have to put in the code is to use tricks such as Enums (C#) to make the code sufficiently clear.

A magic number is a number you use in the code, that is ‘magical’, in the sense that nobody knows where it came from.  Like the above example, 5 is a magic number.

Instead of writing the following code:

int _pageMode;
if (_pageMode == 2) {
    Response.Write("You are in edit mode");
} else if (_pageMode == 3) {
    Response.Write("You are in read only mode");
}

You can write the following C# code to take advantage of enums:

enum Mode {
Default, Edit, ReadOnly
}
Mode _pageMode;

if (_pageMode == Mode.Default)
{
    Response.Write("Default mode");
} else if (_pageMode == Mode.Edit)
{
    Response.Write("Edit mode");
}

There is more to enums, you can give each item in the enum a value as well.  If you are storing your enum in a viewstate or session, you can still use it as an enum.  For example,

if ((Mode)Session["mode"] == Mode.Read)
 
New - Aug 14 07 - Enum is VB.NET is also similarly easy

Declariation

enum Age
Young = 50
Old = 70
TooOld = 90
end enum

or just

enum Season
Fall
Winter
Spring
Summer
IceAge
end enum

Usage VB.NET

if mySeason = Season.Fall then
  'do something
end if

References

  1. enum (C# - msdn)
  2. A nice article on enums by Nishant

It is not necessary to convert the Mode.Read into an integer and then compare it as integer values.

Other Interesting Posts

2 Responses to “Use Enum (C#) instead of magic numbers”

  1. Kamal says:

    Nice article.

  2. sohbet says:

    thanks

Leave a Reply