Enumeration

Enumeration

An enumeration is a set of discrete and related values. Enumerations expand into a type, whereas the members of the enumeration are defined as constant. The default underlying type of an enumeration is integer. An enumeration is never required; integer variables can be used instead. However, enumerations are safer, more extensible, and enhance readability. The Months.GetMonth method outputs the name of a month. The method relies on integer values.

public class Months {
   static public void GetMonth(int iMonth) {
       switch(iMonth) {
           case 1:
               Console.WriteLine("January");
               break;

           case 2:
               Console.WriteLine("Febuary");
               break;
           case 3:
               Console.WriteLine("March");
               break;
           // and so on...
           default:
               Console.WriteLine("Invalid Month");
               break;
        }
    }
}

Here is the Months class rewritten to use an enumeration:

public enum Month {
      January=1,
      February,
      March
  }
  public class Months{
  public static void GetMonth(Month m) {
          Console.WriteLine(m.ToString());
      }
  }

Which version of Months is simpler and more readable?

Here is the syntax of an enumeration:

  • accessibility enum enumname: basetype {memberlist};

Enumerations support public and other accessibility. The default underlying type is integer. The basetype element changes the underlying type. This can be any integral type, except the character type. For the Month enumeration, changing the underlying from integer to byte is more efficient. The memberlist includes all the constants of the enumeration. By default, the constant members are numbered in textual order from zero to n-1. Each member can be assigned a specific value. Here is the updated enumeration called Month:

public enum Month: byte {
    January=1,
    February,
    March
}

When assigning values to enumeration members, sequential ordering is not required. In addition, duplicate values are allowed. Some members can be set without initializing others. The value of the preceding member is incremented and assigned to any unassigned member. ZEnum is a mixture of explicitly and implicitly initialized members. Optional values are listed in the comments.

public enum ZEnum{
    item1=6,
    item2=3,
    item3,    // 4
    item4,    // 5
    item5=8,
    item6     // 9
}

Enumerations are derived from the System.ValueType method, which offers important services for enumeration types. Table 2-5 lists some of those services.

Table 2-5: Important System.Enum Methods

Method Name

Description

static string GetName(Type enumtype, object value)

Returns the string representation of a specific item of the enumeration.

static string[] GetNames(Type enumtype)

Returns a string array containing the string representation of every item of the specified enumeration.

static Array GetValues(Type enumtype)

Returns an array of the underlying type. The array contains the numerical representation of each value of the enumeration.

static Type GetUnderlyingType(Type enumType)

Returns the underlying type of the enumeration.

Bitwise Enumeration

Bitwise enumeration is for mutually inclusive flags. Each member of the enumeration is assigned a unique bitwise value. Apply the flags attribute to an enumeration to specify bitwise enumeration.

Combine bitwise flags using the or operator (|). Confirm the existence of a flag with the bitwise and operator (&).

The following code demonstrates the flags attribute of an enumeration:

using System;

namespace Donis.CSharpBook{

    [Flags] public enum Contribution {
        Pension=0x01,
        ProfitSharing=0x02,
        CreditBureau=0x04,
        SavingsPlan=0x08,

        All=Pension|ProfitSharing|CreditBureau|SavingsPlan
    }

    public class Employee {
        private Contribution prop_contributions;
        public Contribution contributions {
            get {
                return prop_contributions;
            }
            set {
                prop_contributions=value;
            }
        }
    }

    public class Starter{
        public static void Main(){
            Employee bob=new Employee();
            bob.contributions=Contribution.ProfitSharing|
                Contribution.CreditBureau;
            if((bob.contributions&Contribution.ProfitSharing)
                == Contribution.ProfitSharing) {
                Console.WriteLine("Bob enrolled in profit sharing");
            }
        }
    }
}