Chapter 25. Using enums

Java developers may be new to this keyword, though C/C++ users will find it very familiar. Enums are used frequently because it is a very convenient way to represent shared constants.

An enumeration is a collection of int elements. However, unlike other collections or arrays, enums are usually used to assign arbitrary int values to a series of strings, so that they can be used like constants. For example:

 1:  using System;
 2:
 3:  public class TestClass{
 4:    enum Month
 5:      {Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec};
 6:
 7:    public static void Main(){
 8:      Console.WriteLine(Month.Jan);
 9:      Console.WriteLine(Month.Oct);
10:      Console.WriteLine((int)Month.Jan);
11:      Console.WriteLine((int)Month.Oct);
12:    }
13:  }

Output:

c:expt>test
Jan
Oct
0
9

In TestClass, an enum is created consisting of 12 int elements. By default, the first element in the enum will be assigned the value of 0, the second element the value of 1, and so forth. So when Month.Jan is cast into an int and printed out, 0 is displayed. [1]

[1] Enums are seldom printed out in numeric form though. They are very commonly used to give a meaningful name to otherwise meaningless integer values used for classes or methods to communicate.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.152.95