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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With