Personal notes on software development.
For Java technologies check my dedicated site

Pages

Enumerations can provide a powerful alternative to constants. An enumeration is a distinct value type, consisting of a set of named constants (called the enumerator list).
Enumerations let you establish a relation between constants, i.e. instead of doing this:

const int LightJacketWeather = 60;
const int SwimmingWeather = 72;
const int WickedCold = 0;
You can do this:
enum Temperatures
{
   WickedCold = 0,
   FreezingPoint = 32,
   LightJacketWeather = 60,
   SwimmingWeather = 72,
   BoilingPoint = 212,
}
Access the constants with:
Temperatures.BoilingPoint


Technical definition of an enumeration:
[attributes] [modifiers] enum identifier
[:base-type] {enumerator-list};


Example 1:
enum Temperatures
{
   WickedCold = 0,
   FreezingPoint = 32,
   LightJacketWeather = 60,
   SwimmingWeather = 72,
   BoilingPoint = 212,
}

Example 2:
enum ServingSizes :uint
{
   Small = 1,
   Regular = 2,
  Large = 3
}


Note: if not specified, enums default base type is int, but you are free to use any of the integral types (like the uint used in this example) except for char.

Example 3:
public class EnumTest
{
    enum Days { Sat, Sun, Mon, Tue, Wed, Thu, Fri };

    public static void Main()
    {
        Console.WriteLine("Sat = {0}", Days.Sat); //OUT: Sat = Sat
        Console.WriteLine("Fri = {0}", Days.Fri); //OUT: Fri = Fri

        Console.WriteLine("Sat = {0}", (int)Days.Sat); //OUT: Sat = 0
        Console.WriteLine("Fri = {0}", (int)Days.Fri); //OUT: Fri = 6
    }
}

Note: Explicit cast needed to access the values. If no value is defined the default starting value is 0.

Example 4:
public class EnumTest
{
    enum Days { Sat=1, Sun, Mon, Tue, Wed=20, Thu, Fri };

    public static void Main()
    {
        Console.WriteLine("Sat = {0}", (int)Days.Sat); //OUT: Sat = 1
        Console.WriteLine("Tue = {0}", (int)Days.Tue); //OUT: Tue = 4
        Console.WriteLine("Thu = {0}", (int)Days.Thu); //OUT: Thu = 21
        Console.WriteLine("Fri = {0}", (int)Days.Fri); //OUT: Fri = 22
    }
}

Note: if no value is specified the default value will be the previous value+1;

No comments:

Post a Comment