Randy Schouten
Randy Schouten

Reputation: 39

How do I return the enum value that matches a given string?

So I have a string and I want to get a value from an enum to return with the same name as string. Example:

enum Types{
    one,
    two,
    three
}

private Types getType(string value){   //Let's say value is "two"
    return Types.value;                //This should return the enum "two" of Types
}

I hope I made it clear enough!

Upvotes: 2

Views: 309

Answers (2)

dtb
dtb

Reputation: 217243

If you're using .NET 4.0 or later, you can use the Enum.TryParse<TEnum> Method:

Types result;

if (Enum.TryParse<Types>("two", out result))
{
     // result == Types.two
}

Upvotes: 4

I4V
I4V

Reputation: 35353

Use Enum.Parse

var t = (Types)Enum.Parse(typeof(Types), "two");

Upvotes: 10

Related Questions