Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Very basic use of Enum.TryParse doesn't work

Tags:

c#

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:

  • The best overloaded method match for 'System.Enum.TryParse(string, out string)' has some invalid arguments

  • Argument 1: cannot convert from 'System.Type' to 'string'

    public enum PetType
    {
        None,
        Cat = 1,
        Dog = 2
    }
    
    string value = "Dog";
    PetType pet = (PetType)Enum.TryParse(typeof(PetType), value);
    
    if (pet == PetType.Dog)
    {
        ...
    }
    

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

Thanks.

like image 804
Bronzato Avatar asked Nov 30 '22 12:11

Bronzato


1 Answers

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
}
like image 164
Darin Dimitrov Avatar answered Dec 06 '22 04:12

Darin Dimitrov