What is the usage of ENUM in .NET?In your coding,
you will represent constant values using the keyword const. But this keyword
can define only one constant. If you want to specify set of related constants
then you can use enum. The enum is a value type containing set of constants
that are related to one another. The enum can hold values of any integral
type except the type char. Here is an example:
class sampleSeasons { public enum Spring { March, April, May } public enum Summer { June, July, August } public enum Autumn { September, October, November } public enum Winter { December, January, February } public static void Main() { Console.WriteLine("Spring Season occurs in following months:"); foreach (string month in Enum.GetNames(typeof(Spring))) { Console.WriteLine("Month: {0} Value: {1}", month, (int)Enum.Parse(typeof(Spring), month)); } Console.WriteLine("Summer Season occurs in following months:"); foreach (string month in Enum.GetNames(typeof(Summer))) { Console.WriteLine("Month: {0} Value: {1}", month, (int)Enum.Parse(typeof(Summer), month)); } Console.WriteLine("Autumn Season occurs in following months:"); foreach (string month in Enum.GetNames(typeof(Autumn))) { Console.WriteLine("Month: {0} Value: {1}", month, (int)Enum.Parse(typeof(Autumn), month)); } Console.WriteLine("Winter Season occurs in following months:"); foreach (string month in Enum.GetNames(typeof(Winter))) { Console.WriteLine("Month: {0} Value: {1}", month, (int)Enum.Parse(typeof(Winter), month)); Console.ReadLine(); } } Output of this code will be: Spring Season
occurs in following months: In this example, you have defined four seasons as four enumerations each containing the list of months when the season will occur. In this example, note the following: While
defining the enumerations, you have not specified any values for the enum
constants. But in the output you can see that the values are 0, 1, 2 for
each of the constant in each enumeration. How is this value assigned?
By default the first constant in the enum will have the value 0, the next
value will be 1+ the previous constant and so on. However C# provides
you an option to modify the default values. If you want to display January
as 1, February as 2, March as 3 and so on in the order of months in an
year then you can change the enumerations as shown below: Now the output of the code will be: Spring Season
occurs in following months: In
this example, you have not defined any type for the enum. Hence it is
assumed as int by default. However you are allowed to specify type of
an enum as byte or sbyte or short or ushort or int or uint or long or
ulong. Here is an example showing enum of type byte:
|