Enumerations

 
Chapter 2 - C# Basics
bySimon Robinsonet al.
Wrox Press 2002
  

An enumeration is a user-defined integer type. When we declare an enumeration, we specify a set of acceptable values that instances of that enumeration can contain. Not only that, but we can give the values user -friendly names . If, somewhere in our code, we attempt to assign a value that is not in the acceptable set to an instance of that enumeration, the compiler will flag an error. This concept may be new to VB programmers. C++ does support enumerations (or enums), but C# enumerations are far more powerful than their C++ counterparts.

Creating an enumeration can end up saving you lots of time and headaches in the long run. There are at least three benefits to using enumerations instead of plain integers:

  • As mentioned, enumerations make your code easier to maintain by helping to ensure that your variables are assigned only legitimate , anticipated values.

  • Enumerations make your code clearer by allowing you to refer to integer values by descriptive names rather than by obscure 'magic' numbers .

  • Enumerations make your code easier to type, too. When you go to assign a value to an instance of an enumerated type, the Visual Studio .NET IDE will, through IntelliSense, pop up a list box of acceptable values in order to save you some keystrokes and to remind you of what the possible options are.

We can define an enumeration as follows :

   public enum TimeOfDay     {     Morning = 0,     Afternoon = 1,     Evening = 2     }   

In this case, we use an integer value to represent each period of the day in the enumeration. We can now access these values as members of the enumeration. For example, TimeOfDay.Morning will return the value . We will typically use this enumeration to pass an appropriate value into a method, and iterate through the possible values in a switch statement:

   class EnumExample     {     public static int Main()     {     WriteGreeting(TimeOfDay.Morning);     return 0;     }     static void WriteGreeting(TimeOfDay timeOfDay)     {     switch(timeOfDay)     {     case TimeOfDay.Morning:     Console.WriteLine("Good morning!");     break;     case TimeOfDay.Afternoon:     Console.WriteLine("Good afternoon!");     break;     case TimeOfDay.Evening:     Console.WriteLine("Good evening!");     break;     default:     Console.WriteLine("Hello!");     break;     }     }     }   

The real power of enums in C# is that behind the scenes they are instantiated as structs derived from the base class, System.Enum . This means it is possible to call methods against them to perform some useful tasks . Note that because of the way the .NET Framework is implemented there is no performance loss associated with treating the enums syntactically as structs. In practice, once your code is compiled, enums will exist as primitive types, just like int and float .

You can retrieve the string representation of an enum. For example, using our earlier TimeOfDay enum:

   TimeOfDay time = TimeOfDay.Afternoon;     Console.WriteLine(time.ToString());   

This will write out the string Afternoon .

Alternatively you can obtain an enum value from a string.

   TimeOfDay time2 = (TimeOfDay) Enum.Parse(typeof(TimeOfDay), "afternoon", true);     Console.WriteLine((int)time2);   

This code snippet illustrates both obtaining an enum value from a string and converting to an integer. To convert from a string, we need to use the static Enum.Parse() method, which as shown here takes three parameters. The first is the type of enum we wish to consider. The syntax is the keyword typeof followed by the name of the enum class in brackets. We will explore the typeof operator briefly later this chapter and in more detail in Chapters 5. The second parameter is the string to be converted, and the third parameter is a bool indicating whether or not we should ignore case when doing the conversion. Finally, note that Enum.Parse() actually returns an object reference we need to explicitly convert this to the required enum struct (this is an example of an unboxing operation). For the above code, this returns the value 1 as an object, corresponding to the enum value of TimeOfDay.Afternoon . On converting explicitly to an int , this produces the value 1 again.

There are other methods on System.Enum to do things like return the number of values in an enum definition or to list the names of the values. Full details are in the MSDN documentation.

  


Professional C#. 2nd Edition
Performance Consulting: A Practical Guide for HR and Learning Professionals
ISBN: 1576754359
EAN: 2147483647
Year: 2002
Pages: 244

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net