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 ...

Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.