C # Enum.TryParse parsing invalid number strings

With # .NET 4.5, Windows 10, I have the following enumeration:

private enum Enums { A=1, B=2, C=3 } 

And this program behaves very strange:

 public static void Main() { Enums e; if (Enum.TryParse("12", out e)) { Console.WriteLine("Parsed {0}", e); } else { Console.Write("Not parsed"); } Console.ReadLine(); } 

I expect the result of the TryParse method to be false, but to my surprise, the parsing 12 is displayed on the console. In the "Watch" window, it even shows that the value is "12" and it is of type Enums!

This is true for any number line I tried (for example, "540"), but not for lines containing letters ("A12", "12A").

I can easily overcome this by first checking to see if this is a number string, but why is this behavior? Is it for design?

Thanks! Ido

+7
enums c #
source share
2 answers

Enumerations are stored internally as integers, so the likelihood of TryParse returning true for the transmitted integers is.

Regarding why any whole works, it is by design. From MSDN (my attention):

When this method returns, the result contains an object of type TEnum whose value is represented by the value if the parsing operation is successful. If the analysis operation is not performed, the result contains the default value for the base type TEnum. Note that this value should not be a member of the TEnum enumeration . This parameter is passed uninitialized.

+6
source share

A variable or field of an enumeration type can contain any value of its base type, so storing the value 12 in a variable of type Enums is completely legal in your case:

 var e = (Enums) 12; var i = (int) e; // i is 12 

Consequently, Enum.TryParse should be able to parse any value of type int (or any underlying integer type used in your enumeration).

If you want to reject values ​​that have no representation in your enumeration, check them with Enum.IsDefined .

+2
source share

All Articles