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

 

7 Responses to Use Enum (C#) instead of magic numbers

  1. Kamal says:

    Nice article.

  2. sohbet says:

    thanks

  3. Ross says:

    It should be pointed out that using Enum values will bloat up the ViewState quickly. This is because ASP.Net needs to store the enum’s type information inside the ViewState.

    • Ross that’s not true. An enum is simply a shortcut for a value. I believe it’s replaced by the compiler at compile time. There is absolutely no viewstate involved. To test this, disable viewstate and see if enums still work. Of course they do :)

  4. [...] Great read here about not using "magic numbers" – use Enums [...]

  5. Today is very lucky to me.Good share, great article, very usefull for me.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


2 + = 11

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>