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#?
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.
Conclusion. In this blog post, we introduced the enum type and C# limitation of not being able to assign it a string value type.
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.
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.
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(' ', '_'));
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(" ", "_"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With