Search code examples
c#.netenums.net-4.5

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?


Solution

  • 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 :)