Sunday, 3 September 2017

c# - How do I convert a string to an enum value to an integer?











I have declare an enumeration:-



public enum Car
{
SELECT = 0,

AUDI = 1,
NISSAN = 2,
HONDA = 3,
LINCOLN = 4
}


Now I need the int value of enum where it matches:-



private int GetCarType(string CarName)

{
foreach(var item in Enum.GetNames(typeof(Car))
{
if (item.ToLower().Equals(CarName.ToLower()))
//return int value of Enum of matched item; ???????
}


Result expected:-




int i = GetCarType(CarName); //suppose CarName is AUDI, it should return 1;
Console.write(i);

Result :- 1


How will I get value of enum? And better coding practice.


Answer



var result = (int)System.Enum.Parse(typeof(Car), carName)



http://msdn.microsoft.com/en-us/library/essfb559.aspx



This replaces your GetCarType function. You no longer have to iterate over the enum names.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...