3

trying to compile this code but the if statement coughs up an error:

Error 1 Operator '==' cannot be applied to operands of type 'object' and..

public enum ShoeType
{
    soccer = 0,
    jogging=1,
    fitness=2
}

class Program
{
    static void Main(string[] args)
    {
        string shoetype = "1";

        if (Enum.Parse(typeof(ShoeType), shoetype) == ShoeType.jogging)
        {
            var test = "gotcha";
        }
    }
}

2 Answers 2

5

If you look at the docs you can see the Enum.Parse method is defined to return an Object, so you have to cast the result to the type you want. Like this:

(ShoeType)Enum.Parse(typeof(ShoeType), shoetype)

You could also use the TryParse method and use the Boolean result to see if the parse was successful:

ShoeType type;
if (Enum.TryParse(shoetype, out type) && type == ShoeType.jogging)
{
    var test = "gotcha";
}
2

try this:

if ( (ShoeType) Enum.Parse(typeof(ShoeType), shoetype) == ShoeType.jogging)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.