-2

I have the following Enum:

public enum ItemType
{
   Foo =0,
   Bar =1
}

and then a string that is passed to a method in lowercase.

How can I compare the string to my enum and return the enum.

public ItemType Method(string value)
{
   ///compare string to enum here and return Enum
} 

and the method receives the value as parameter like this (notice the lowercase)

string value = "foo";  /// or value ="bar"

ItemType type = Method(value)
user2818430
  • 5,853
  • 21
  • 82
  • 148

1 Answers1

-1

You are looking for Enum.TryParse method.

public ItemType Method(string value)
{
    ItemType item;
    if(Enum.TryParse(value, true, out item)) return item;

    else /* throw exception or return defaul value  */
}

The second parameter is allows you to perform case insensitive search.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184