Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to enum conversion in C#

Tags:

c#

enums

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#?

like image 428
Naveen Avatar asked Jul 27 '09 08:07

Naveen


People also ask

How do I convert string to enum?

Use the Enum. IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.

Can we assign string to enum?

Conclusion. In this blog post, we introduced the enum type and C# limitation of not being able to assign it a string value type.

How do you convert a string value to a specific enum type in C #?

To convert string to enum use static method Enum. Parse. Parameters of this method are enum type, the string value and optionally indicator to ignore case.

What is enum TryParse?

Converts the span of characters representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. TryParse(Type, String, Object) Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.


2 Answers

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(' ', '_')); 
like image 151
mmx Avatar answered Sep 28 '22 18:09

mmx


Operation enumVal = (Operation)Enum.Parse(typeof(Operation), "Equals") 

For "Not Equals", you obv need to replace spaces with underscores in the above statement

EDIT: The following version replaces the spaces with underscores before attempting the parsing:

string someInputText; var operation = (Operation)Enum.Parse(typeof(Operation), someInputText.Replace(" ", "_")); 
like image 28
AdaTheDev Avatar answered Sep 28 '22 17:09

AdaTheDev