find and solve || findandsolve.com
Please wait.....

C# | Enumeration (or enum)

In the C#, Enum (or Enumeration) is a value data type in C#. It is mainly used to assign the names or string values to integral constants, which make a program easy to read and maintain. Enumeration is declared using the enum keyword directly inside a namespace, class, or structure.

Enum constants have default values that start from 0 and are incremented one by one. But we can change the default value.

Points to remember

  • num has fixed set of constants
  • enum improves type safety
  • enum can be traversed


C# Enum Example

using System;  
public class EnumExample
{
    public enum DayOfWeek{ Saturday, Sunday, Monday}
    public static void Main()
    {
        int x = (int)DayOfWeek.Sunday;
        int y = (int)DayOfWeek.Saturday;
        Console.WriteLine("Sunday= {0}", x);
        Console.WriteLine("Saturday= {0}", y);
    }
}  

Ouput

Sunday= 1

Saturday= 0

C# enum example changing start index

using System;  
public class EnumExample
{
    public enum DayOfWeek{ Saturday=3, Sunday, Monday}     public static void Main()
    {
        int x = (int)DayOfWeek.Sunday;
        int y = (int)DayOfWeek.Saturday;
        Console.WriteLine("Sunday= {0}", x);
        Console.WriteLine("Saturday= {0}", y);     }
}  

Output

Sunday= 4

Saturday= 3

C# enum example: traversing all values using getNames()

using System;  
public class EnumExample
{
    public enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };     public static void Main()
    {
        foreach (string s in Enum.GetNames(typeof(Days)))
        {
            Console.WriteLine(s);
        }
    }
}

Output

Sunday

Monday

Tuesday

Wednesday

Thursday

Friday

Saturday

C# enum example: traversing all values using getValues()

using System;  
public class EnumExample
{
    public enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };     public static void Main()
    {
        foreach (Days d in Enum.GetValues(typeof(Days)))         {
            Console.WriteLine(d);
        }
    }
}

Output

Sunday

Monday

Tuesday

Wednesday

Thursday

Friday

Saturday