C#

C# Enumerations

The objective of this article is to familiarize you with the C# Enum, short for enumeration. You will learn how to declare, create and use C# enumerations, including code examples of the commonly used methods and operators. Finally, look at the different ways to iterate through enumeration members.

C# Enumeration, or enum for short, is a custom data type that allows you to group fixed set of name-value pairs. You use enum keyword to define a new value type of enumeration, which is strongly typed that prevents many errors, and makes the code easier to read and understand.

Important

  • Derives from System.Enum class.
  • Enums are defined directly inside a namespace or a class.
  • C# Enumerations can be defined in a separate file.
  • Enum cannot contain two members with the same name but duplicate value is allowed.
  • Enum of one type cannot be implicitly assigned to an enum of another type.
  • Abstract and sealed modifiers are not permitted in an enum declaration.

C# Enumeration Syntax

You define an enumeration by using the enum keyword, followed by a name, and a set of possible values that the type can have, inside of curly braces and separated by commas. Each enum member has a name and associated constant value; the name is the string and the value is a zero-based integer. By default, each member is automatically assigned a value according to the order in which it is defined, starting from zero.

Each enumeration has an underlying type used for storage. Each of the values that an enumeration type can take is stored as a value of this underlying type, which by default is int. You can specify a different type by using a colon after the enumeration’s name followed by the desired integer type. The valid base types for enumeration are byte, sbyte, short, ushort, int, uint, long, or ulong.

The following example defines a new type of enumeration called Planets with 5 named constants. By default, the first element has the value 0, and each subsequent element has one value higher. In the following enumerator list, the value of Mercury is 0, Venus is 1, Earth is 2, and so on.

enum Planets { Mercury, Venus, Earth, Mars, Jupiter}

Additionally, you can specify different values for each member names if you want by simply giving them integer values at the time of declaration. Now, Mercury is assigned a value of 11, Venus is 12, and so forth.

enum Planets { Mercury = 11, Venus = 12, Earth = 13, Mars = 14, Jupiter = 15 }

You can assign value to some of the enum members, any member left unassigned is automatically given a value that is one greater than the last assigned value. In the following code, Mercury is initialized with the value 1 and Venus 2. As you did not assign values for Earth to Jupiter, consecutive numbers after 2 will be assigned to them. That is Earth = 3, Mars = 4 and so on.

enum Planets { Mercury = 1, Venus = 2, Earth, Mars, Jupiter }

After you have declared an enumeration, you can use it in the same way you do any other type. If the name of your enumeration is Planets, you can create variables of type Planets just by declaring a variable using this new enum type, as follows:

Planets planet;

You can create a nullable version of an enumeration variable by using the ? modifier and then assigning a null value to it:

Planets? planet = null;

To assign a value to the enum variable, you will use the “.” Operator to access Planets elements. The elements are accessed from the enum as if they were static members of a class. You cannot set the value that is not defined directly by the enumerated type.

planet = Planets.Mercury; // implicit cast

// OR: using var

var planet = Planets.Mercury;

If you are interested to retrieve the integer value of a given constant, you must explicitly cast the enum constant to its underlying data type like this.

int planetNumber = (int)Planets.Mercury; // explicit cast

// To get name from associated value

Planets planet = (Planets)planetNumber; // explicit cast

// OR: using var

var planet = (Planets)planetNumber;

Run Demo

ToString(), IsDefined(), And TryParse() Methods

C# enumeration supports a method called ToString(), which explicitly converts current enumeration constant to a string that represents its name.

Planets planet = Planets.Mercury;
string strPlanet = planet.ToString();// Mercury
// OR
string strPlanet = Planets.Mercury.ToString();// Mercury

Enum.IsDefined is another useful method that returns a Boolean value of True/False if a given integral value, or its name, found is actually a member of enumeration.

Console.WriteLine(Enum.IsDefined(typeof(Planets), Planets.Mercury)); // True
Console.WriteLine(Enum.IsDefined(typeof(Planets), "Earth")); // True
Console.WriteLine(Enum.IsDefined(typeof(Planets), "Neptune")); // False
Console.WriteLine(Enum.IsDefined(typeof(Planets), 1)); // True
Console.WriteLine(Enum.IsDefined(typeof(Planets), 20)); // False

Enum.TryParse method which takes two parameters; the first is the string to be parsed and the second is a variable with the out keyword to be filled with the value returned if the conversion succeeds.

This method converts the string representation of the name or number of enumeration member to an equivalent enumeration object.

You can use TryParse or Parse methods because both are identical, except that Parse throws an exception if the conversion fails whereas will not throw any exception, instead returns a Boolean value of false.

Syntax

Enum.TryParse(string, TEnum)
// OR
Enum.Parse(Type, String)

Planets planet;
if (Enum.TryParse<Planets>("2", out planet))
{
    if (Enum.IsDefined(typeof(Planets), planet))
        Console.WriteLine($"{planet} found.");
    else
        Console.WriteLine("Unknow Planet.");
}

Method returns false if the string name does not represent a named constant of enumeration. On the other hand, if value is the string representation of an integer that does not represent an underlying value of enumeration, than the method returns that value converted to an integral type. Now, you can use Enum.IsDefined method to check if converted integer is actually a member of enumeration.

OUTPUT

Earth found.

C# Operators

C# Operators can be used on the values of enum types : ==, !=, <, >, <=, >=, binary +, binary -, ^, &, |, ~, and ++ and –

enum Numbers { One = 1, Two = 2, Three = 3, Four = 4, Five = 5 }

Console.WriteLine($"== : {Numbers.One == Numbers.Three}"); // False
Console.WriteLine($"!= : {Numbers.One != Numbers.Two}"); // True
Console.WriteLine($">= : {Numbers.Four >= Numbers.Five}"); // False
Console.WriteLine($"<= : {Numbers.Two <= Numbers.Four}"); // True
Console.WriteLine($"> : {Numbers.Four > Numbers.Three}"); // True
Console.WriteLine($"< : {Numbers.Five < Numbers.One}"); // False

Console.WriteLine($"- : {Numbers.Five - Numbers.One}"); // 4
Console.WriteLine($"& : {Numbers.Five & Numbers.One}"); // One
Console.WriteLine($"| : {Numbers.Five | Numbers.One}"); // Five

int Three = (int)Numbers.Three;
int Four = (int)Numbers.Four;

Console.WriteLine($"Three++ : {Three++}"); // 3
Console.WriteLine($"++Three : {++Three}"); // 5
Console.WriteLine($"Four-- : {Four--}"); // 4
Console.WriteLine($"--Four : {--Four}"); // 2
Console.WriteLine($"~Four : {~Four}"); // -3

Run Demo

C# switch Statement

The following code uses the planet variable in a C# switch Statement.

var planet = Planets.Earth;

switch (planet)
{
    case Planets.Mercury:
        Console.WriteLine("Mercury found.");
        break;
    case Planets.Venus:
        Console.WriteLine("Venus found.");
        break;
    case Planets.Earth:
        Console.WriteLine("Earth found.");
        break;
    case Planets.Mars:
        Console.WriteLine("Mars found.");
        break;
    case Planets.Jupiter:
        Console.WriteLine("Jupiter found.");
        break;
    default:
        Console.WriteLine("Unknow planet");
        break;
}

Run Demo

OUTPUT

Earth found.

Iteration

If you want to iterate over enumeration members, you will have to use the enum type and its methods. Use the typeof keyword to fetch the underlying type of the enum in order to manipulate it during run-time. Call the GetNames or GetValues method to retrieve the value names.

enum Planets { Mercury = 1, Venus = 2, Earth = 3, Mars = 4, Jupiter = 5 }
  • GetNames method to retrieve a string array containing the names of the enumeration members.
  • Parse method to convert the string to its equivalent enumeration value.
string[] names = Enum.GetNames(typeof(Planets));
foreach (var name in names)
{
    Planets status = (Planets)Enum.Parse(typeof(Planets), name);
    Console.WriteLine($"{status} ({status:D})");
}

// OR

  • GetValues method to retrieve an array that contains the underlying values in the enumeration.
  • ToObject method to convert the integer to its equivalent enumeration value.
var planets = Enum.GetValues(typeof(Planets));
foreach (Planets planet in planets)
    Console.WriteLine($"{planet} ({planet:D})");
// OR
foreach (Planets planet in Enum.GetValues(typeof(Planets)))
    Console.WriteLine($"{planet} ({planet:D})");

Run Demo

Prints out the enum member names and their associated values. The output is

OUTPUT

Mercury (1)
Venus (2)
Earth (3)
Mars (4)
Jupiter (5)

Multiple enum members may share the same underlying value. The example shows an enum in which computed values have been used.

enum Numbers
{
    One = 1,
    Two = 2,
    Three = One + Two,
    Four = Two + One + 1,
    Five = Two + 4 - 1
}

Run Demo

OUTPUT

One (1)
Two (2)
Three (3)
Four (4)
Five (5)

More Examples

The following examples declare an enum with an underlying type of int and byte.

// A custom enumeration. 
enum Menu
{
   Home,    // = 0  
   Insert,  // = 1
   Design,  // = 2
   Layout,  // = 3
   View     // = 4
}
// Browsers map to an underlying type byte. 
enum Browsers : byte
{
   Chrome = 11,
   Edge = 1,
   Safari = 110,
   Netscape = 40
}
enum Alphabet
{
   A = 4,
   B = 5,
   C,     // = 6
   D,     // = 7
   E      // = 8
}
enum Movies
{
    Alpha = 2,
    Nun = 3,
    AXL = Alpha + Nun,
    JurassicWorld = AXL + 8,
}

Run Demo

C# Reference | Microsoft Docs

Sending
User Rating 5 (1 vote)
Tagged in :

Add Comment

Click here to post a comment

Send this to a friend