C# enum

Enum in C# is also known as enumerations. It basically refers to a named set of constants such as months, days, seasons, etc. Enum improves type safety. They contain fixed set of constants and they can be traversed. We can define Enum outside or within the class or structs. Let's see a simple example of enum in C#.


C# Enum Example:
using System;
public class EnumExample 
{
public enum months {january,february,march,april,may,june,july,august,september,october,november,december};
            public static void Main (string[] args)
            {
                        int x=(int)months.january;
                        int y=(int)months.february;
                        int z=(int)months.march;
                        Console.WriteLine("January="+x);
                        Console.WriteLine("February="+y);
                        Console.WriteLine("March="+z);
            }
}
Output
January=0
February=1
March=2
C# Enum Example: Traversing all values
using System;
public class EnumExample 
{
public enum months{january,february,march,april,may,june,july,august,september,october,november,december};
            public static void Main (string[] args)
            {
                        foreach(string s in Enum.GetNames(typeof(months)))
                                    {
                                                Console.WriteLine(s);
                                    }                                              
            }
}
Output
january
february
march
april
may
june
july
august
september
october
november
December