Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse enum when string is lowered

I have a pretty fun problem, which I am not sure you can even solve using this approach.

I have some string, which is all lowercase. Let's just call it businesslaw. Now, I have an enum type, where the value is BusinessLaw.

What I want to do, is to convert the businesslaw string, into a BusinessLaw enum type.

Normally I would approach it by doing this:

return (EnumType) (Enum.Parse(typeof (EnumType), value));

However, that is not possible when there is some case difference.

How would you solve this issue? Or is it by nature, unsolveable?

like image 963
Lars Holdgaard Avatar asked Oct 12 '13 15:10

Lars Holdgaard


1 Answers

You can use the overload of Enum.Parse with a final parameter to indicate case-sensitivity:

return (EnumType) (Enum.Parse(typeof (EnumType), value, true));

There's a similar TryParse overload.

However, bear in mind that there could be multiple enum values with the same name other than case:

public enum Awkward
{
    FOO,
    foo,
    Foo,
    fOO
}

You should probably avoid having such enum values if possible :)

like image 60
Jon Skeet Avatar answered Oct 12 '22 16:10

Jon Skeet