DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

read int value from enum - C#.NET Example

By Ashok Nalam on 16 Dec 2013 | Category: C# | Tagged: enum .NET extension-methods parsing casting 
The snippet shows how to read enum value using casting, Enum.Parse and Extension method.
  Discuss Add Comment   |  
Add rating Rate this resource   
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

  Discuss Add Comment    
Add rating Rate this resource   
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 9226  (Professional)
Location : INDIA
Home Page : http://dotnetmirror.com
About : I am admin of this site.
Rate this resource
 
Add your Comment
Name Email WebSite
Captcha Refresh


Comments (0)
No comments found, click here to add comment.
 
cheap jordans|wholesale air max|wholesale jordans|wholesale jewelry|wholesale jerseys