Very simple use of Enum.TryParse does not work

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?

Thank.

+3
c #
Jul 01 '13 at 8:57
source share
3 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 the out parameter to save 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 } 
+13
Jul 01 '13 at 8:59
source share

First of all, it should be noted that TryParse returns a bool, not a Type your enum.

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

+4
Jul 01 '13 at 9:00
source share

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.

+2
Jul 01 '13 at 9:06 on
source share



All Articles