I am using a 3rd party DLL which expects an enumeration called 'DaysOfWeek' in the method signature.
I am allowing my users to select the day of week from a ComboBox, but I end up with a string.
How can I match my string to the appropriate enumeration property?
Thanks!
You can create Enum from String by using Enum. valueOf() method. valueOf() is a static method that is added on every Enum class during compile-time and it's implicitly available to all Enum along with values(), name(), and cardinal() methods.
To compare a string with an enum, extend from the str class when declaring your enumeration class, e.g. class Color(str, Enum): . You will then be able to compare a string to an enum member using the equality operator == .
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.
The valueOf() method of the Enum class in java accepts a String value and returns an enum constant of the specified type.
Enum.Parse(typeof(DaysOfWeek), yourStringValue, true);
Note: This will launch an exception if the string is not convertible to the enum. Last parameter is for case insensitive search.
You can use the following to convert a string to an enum:
DaysOfWeek value = (DaysOfWeek)Enum.Parse( typeof(DaysOfWeek), enumAsString );
You can also use the case-insensitive overload if users may type in theor own values:
DaysOfWeek value = (DaysOfWeek)Enum.Parse( typeof(DaysOfWeek), enumAsString, true );
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