Parse enum from String not working

I have a public enum declared like this:

public enum States
    {
        SomeState,
        SomeOtherState
    }

Having an arbitrary string myString which may represent any of the "States" above, I'd like to write a switch to check which one it currently is.

This is my attempt.

States state = Enum.Parse(States, myString, true);
            switch (state)
            {
                case States.SomeState:
                case States.SomeOtherState:
                    break;
                default:
                    break;
            }

Inside of the Enum.Parse() it tells me that the argument State is being used as a type instead that as a variable. Isn't that the correct usage? The first argument Enum.Parse is supposed to receive is Type enumType: why then it tells me it needs a variable?


Many kind replies indicates to use typeof. Unfortunately, I've already tried that but since I receive the following error I guessed it was a wrong idea.

Enum.Parse(typeof(States), myString, true);

yields:

cannot implicitly convert type 'object' to 'States'. An explicit conversion exists.


Solution 1:

Yes, you need to send in the Type of enum that your are parsing into (using typeof):

States state = (States)Enum.Parse(typeof(States), myString, true);

The Parse method is expecting an argument of type System.Type. Not the type States.

Here is the signature from the docs.

[ComVisibleAttribute(true)]
public static Object Parse(
    Type enumType,
    string value,
    bool ignoreCase
)

Parse returns an object so it requires you to cast to your type after the parse.

Solution 2:

Can make it more elegant by using extension class like so:

namespace YourClass.Models;

public static E ToEnum<E>(this object value, bool ignoreCase = true) where E : Enum
{
    if(value == null)
    {
        throw new ArgumentNullException("Value cannot be null");
    }
    return (E)Enum.Parse(typeof(E), value.ToString(), ignoreCase);
}
And using it like so:
States state = myString.ToEnum<States>();