Bronzato
Bronzato

Reputation: 9332

Very basic use of Enum.TryParse doesn't work

I found a very basic code as described below and I cannot get it to work in my c# windows Forms solution. I got the errors:

I don't understand where is the problem. The errors are all on the Enum.TryParse line. Any idea?

Thanks.

Upvotes: 5

Views: 16707

Answers (3)

Roni
Roni

Reputation: 21

I think you ment to use Enum.Parse:

 PetType pet = (PetType)Enum.Parse(typeof(PetType), value);

TryParse only returns true if parsing succeeded, false otherwise.

Upvotes: 2

Jamie Dixon
Jamie Dixon

Reputation: 53991

The first thing to note is that TryParse returns a bool not the Type of your enum.

The out parameter must point to a variable that is the Type of the enum.

Upvotes: 4

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

As you can see from the documentation, Enum.TryParse<TEnum> is a generic method that returns a boolean property. You are using it incorrectly. It uses an out parameter to store the result:

string value = "Dog";
PetType pet;
if (Enum.TryParse<PetType>(value, out pet))
{
    if (pet == PetType.Dog)
    {
        ...
    }
}
else
{
    // Show an error message to the user telling him that the value string
    // couldn't be parsed back to the PetType enum
}

Upvotes: 15

Related Questions