Alex Rivera | Logout

String to enum conversion in C#

Asked 2009-07-27T08:36:39.723
49

I have a combo box where I am displaying some entries like:

Equals
Not Equals 
Less Than
Greater Than

Notice that these strings contain spaces. I have a enum defined which matches to these entries like:

enum Operation{Equals, Not_Equals, Less_Than, Greater_Than};

Since space is not allowed, I have used _ character.

Now, is there any way to convert given string automatically to an enum element without writing a loop or a set of if conditions my self in C#?

Edit
Report

1 Answer

91

I suggest building a Dictionary<string, Operation> to map friendly names to enum constants and use normal naming conventions in the elements themselves.

enum Operation{ Equals, NotEquals, LessThan, GreaterThan };

var dict = new Dictionary<string, Operation> {
    { "Equals", Operation.Equals },
    { "Not Equals", Operation.NotEquals },
    { "Less Than", Operation.LessThan },
    { "Greater Than", Operation.GreaterThan }
};

var op = dict[str]; 

Alternatively, if you want to stick to your current method, you can do (which I recommend against doing):

var op = (Operation)Enum.Parse(typeof(Operation), str.Replace(' ', '_'));
answered 2009-07-27T08:38:39.047

Your Answer