The snippet shows how to read enum value using casting, Enum.Parse and Extension method.
public enum TimeOfDay
{
Morning = 1,
Afternoon = 2,
Evening = 3,
Night = 4
} Read using Cast:int eveTimeVal = (int)TimeOfDay.Evening;
Console.WriteLine(eveTimeVal); //output: 3; Read using Enum.Parse:TimeOfDay timeEve = (TimeOfDay)Enum.Parse(typeof(TimeOfDay), "Evening");
Console.WriteLine((int)timeEve); //output: 3; Reading using Extension method:public static class EnumExtensions
{
public static int GetEnumValue(this TimeOfDay timeOfDay)
{
return (int)timeOfDay;
}
}
int value = TimeOfDay.Evening.GetEnumValue();
Console.WriteLine(value); //output: 3; Overall Example:using System;
namespace DotNetMirror
{
class ReadEnumIntValue
{
static void Main()
{
//Using casting
int eveTimeVal = (int)TimeOfDay.Evening;
Console.WriteLine(eveTimeVal); //output: 3;
//Using Enum.Parse
TimeOfDay timeEve = (TimeOfDay)Enum.Parse(typeof(TimeOfDay), "Evening");
Console.WriteLine((int)timeEve); //output: 3;
//using Extenstion Method
int value = TimeOfDay.Evening.GetEnumValue();
Console.WriteLine(value); //output: 3;
Console.ReadKey();
}
}
public enum TimeOfDay
{
Morning = 1,
Afternoon = 2,
Evening = 3,
Night = 4
}
public static class EnumExtensions
{
public static int GetEnumValue(this TimeOfDay timeOfDay)
{
return (int)timeOfDay;
}
}
} Output:3 3 3
|