1. Home
  2. Computing & Technology
  3. C / C++ / C#

C# Tutorial - Learn the Fundamentals of Programming

By David Bolton, About.com

4 of 10

All About Enums

Based on integers, enums are similar to enums in C and C++. Instead of using ints directly, enums are used for a smaller range of values. For example traffic lights have red, yellow and green colors. You might consider an int with values 0,1 or 2 for the three colors. But if you accidentally assign 4, the compiler has no way of detecting the error at compile time and the run-time bug is harder to track down and fix.

But if you specify an enum type with three values: red, yellow and green then the compiler will not permit a variable of this type to be assigned any other value. Internally the compiler will assign the values 0,1 and 2 to these colors unless you specify different values for instance 10,15 and 99. It is a very good rule though to always assign a value of 0 to your first enum. If the variable is not explicitly initialized, it defaults to 0 and if this isn't a valid enum value then you have a problem and it may cause an exception.

The code below shows the traffic lights with a color of Off. Note in this example Colors.Yellow has not been given an explicit value, and the compiler uses the next value in the sequence which is 2. When specifying enums, unlike C or C++, you must always prefix the enumerate value with its type. Eg

Colors.Yellow
   enum Colors {Off=0, Red = 1, Yellow, Green = 4 };

   static void Main(string[] args)
   {
       Colors Lights = Colors.Yellow;
       Console.WriteLine("Lights is {0} {1}",Lights,(int)Lights) ;
       Console.ReadLine() ;
   }
In example two calling WriteLine() on an enum calls its .ToString() method. When you run this program it outputs
Yellow 2

Download Example 2

On the next page : Floating Point Numbers

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. All About Enums

©2009 About.com, a part of The New York Times Company.

All rights reserved.