Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match string to enumeration?

Tags:

c#

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!

like image 719
user53885 Avatar asked Dec 22 '09 17:12

user53885


People also ask

How do I convert string to enum?

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.

How do I compare string values to enums?

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 == .

Can we assign string to enum?

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.

Can we convert string to enum in Java?

The valueOf() method of the Enum class in java accepts a String value and returns an enum constant of the specified type.


2 Answers

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.

like image 73
rui Avatar answered Oct 16 '22 12:10

rui


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 );
like image 28
LBushkin Avatar answered Oct 16 '22 11:10

LBushkin