5

Possible Duplicate:
How do I Convert a string to an enum in C#?
Enums returning int value

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.

Community
  • 1
  • 1
user1327064
  • 4,187
  • 5
  • 20
  • 30

4 Answers4

6

If you are converting a string to an enum, you should use Enum.Parse rather than iterating over the names.

Then just cast to an integer:

var iAsInteger = (Int32)i;
Chris Shain
  • 50,833
  • 6
  • 93
  • 125
3

simply cast your enum to int like

int i=(int)Car.Audi;

this will give you 1

int i=(int)Car.Select;

this will give you 0

Devjosh
  • 6,450
  • 4
  • 39
  • 61
3
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.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
1
int i = (int) Enum.Parse(typeof(Car), "AUDI");
David Brabant
  • 41,623
  • 16
  • 83
  • 111