Enum is also known as enumeration that consists of a set of named integral constants. In C#, enumerations are value data types. The keyword enum
is used to define these data types.
The is mainly used to assign the names or string that makes the code more maintainable and readable. For example, we can create an enum for seasons (spring, summer, autumn, winter), or for days(Monday, Tuesday, ….), etc.
The constant in it is the fixed set of constants and is also known as an enumerator. Enum can also be traversed.
Syntax of enums
enum enum_name{const1, const2, ....... };
enum_name
: Name of the enum given by the user.const1, const2
: These are the value of type enum_name, separated by comma.
Let us see an example to define enum.
enum season { spring, summer, autumn, winter };
The above is the enum for the season, spring, summer, autumn
and winter
are the types of the season and by default, the value starts in increasing order from zero such as spring is 0, summer is 1, autumn is 2 and winter is 3.
Example 1: C# program for enum
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | using System; public class EnumEg { public enum Season { Spring, Summer, Autumn, Winter } public static void Main() { int firstSeason = (int) Season.Spring; int lastSeason = (int) Season.Winter; Console.WriteLine("Spring: {0}", firstSeason); Console.WriteLine("Winter: {0}", lastSeason); } } |
Output:
Spring: 0
Winter: 3
As you can see that the default numbers assigned to the constant are shown according to the access. Spring is first on the list so it is 0 and And Winter is at fourth on the list so it is 3 (n-1, starts at 0).
Example 2: C# program for enum to change the index
We write a program to change the default indexing of constants in an enum.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | using System; public class EnumEg { public enum Season { Spring = 10, Summer, Autumn, Winter } public static void Main() { int firstSeason = (int) Season.Spring; int secondSeason = (int) Season.Summer; int lastSeason = (int) Season.Winter; Console.WriteLine("Spring: {0}", firstSeason); Console.WriteLine("Summer: {0}", secondSeason); Console.WriteLine("Winter: {0}", lastSeason); } } |
Output:
Spring: 10
Summer: 11
Winter: 13
Now we assign 10 to spring in the list, and from here the increment starts summer becomes 11, and so on. Also, can be seen in the output.
Example 3: C# program for enum use of getValues()
We will use getValues and get all the values present in the enum of the season.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | using System; public class EnumEg { public enum Season { Spring = 10, Summer, Autumn, Winter } public static void Main() { foreach(Season s in Enum.GetValues(typeof(Season))) { Console.WriteLine(s); } } } |
Output:
Spring
Summer
Autumn
Winter