Reputation: 9332
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.
Upvotes: 5
Views: 16707
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
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
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