enum in C#

By   Calendar icon Aug 31, 2019   Level 1 icon

Description:

We explain here the enumeration type in C# and give some examples of use.

Preferencesoft

enum type

In this article, we explain what an enumerated type is in C# language and we give examples of enum usage.

Enumerated type

An enumerated type in C# represents integer data that belong to a finite set of named constants of integer. At the declaration of an enumerated type, these constants are ordered in a list and are automatically numbered. A variable of this type can only take one of the numbers from that list as a value. This allows more control over the possible values of an integer variable.

Declaring enum type and variable

The syntax for declaring an enumerated type is

public enum <enum_type_name> {
    <name_1>, .., <name_N>
};
  1. Where enum_type_name is the name of the enumerated type.
  2. <name_1>, .., <name_N> are identifiers representing the integer values of the enumeration. By default, the first value of the enumeration is 0.

It is possible to change the values associated with the identifiers of the enumeration.

public enum <enum_type_name> {
    <name_1>=<value_1>, .., <name_N>=<value_N>
};

Example

enum Drink
{
    espresso,
    doubleEspresso,
    granLungo,
    coffee,
    alto
}

Example

using System;
namespace EnumExample
{
enum Drink
{
    espresso,
    doubleEspresso,
    granLungo,
    coffee,
    alto
}
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        Drink choice = Drink.espresso;
        Console.WriteLine("Do you want a coffee? (Y/N) ");
        string ans=Console.ReadLine();
        if (ans=="Y" || ans=="y")
            choice = Drink.coffee;
        Console.WriteLine("{0} is ready", choice);
        Console.ReadKey();
    }
}
}

Enum and integer types

An enum type is by default constructed from integers. But we can define it from other types of integers: byte, sbyte, short, ushort, int, uint, long or ulong.

Converting string to enum in C#

It is possible to convert a string of characters into enum type with the Parse method of enum.

Converting enum to string in C#

To convert an enum value to a string, use the ToString method.

Iterating through enum

Example

using System;
namespace EnumExample
{
enum Drink
{
    espresso,
    doubleEspresso,
    granLungo,
    coffee,
    alto
}
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        Console.WriteLine("Select, a hot drink");
        foreach (string d in Enum.GetNames(typeof(Drink)))
            Console.WriteLine(d);
        Console.WriteLine("\nPress Any Key to Exit..");
        Console.ReadKey();
    }
}
}

CSharp

Categories