I found very simple code, as described below, and I cannot get it to work in my C # windows Forms solution. I got errors:
The best overloaded method match for 'System.Enum.TryParse (string, out string)' has some invalid arguments
Argument 1: cannot be converted 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 do not understand where the problem is. All errors are in the line Enum.TryParse . Any idea?
Enum.TryParse
Thank.
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 the out parameter to save the result:
Enum.TryParse<TEnum>
out
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 }
First of all, it should be noted that TryParse returns a bool, not a Type your enum.
TryParse
Type
The out parameter must point to a variable that is Type enum .
enum
I think you are using Enum.Parse:
PetType pet = (PetType)Enum.Parse(typeof(PetType), value);
TryParse returns true only if the parsing is complete, and false otherwise.