C# Enum.TryParse parses invalid number strings
Internally, enums are stored as integers so that's likely why TryParse is returning true for integers being passed in.
Regarding why any integer is working, it's by design. From MSDN (emphasis mine):
When this method returns, result contains an object of type TEnum whose value is represented by value if the parse operation succeeds. If the parse operation fails, result contains the default value of the underlying type of TEnum. Note that this value need not be a member of the TEnum enumeration. This parameter is passed uninitialized.
A variable or field of an enumeration type can hold any values of its underlying type, so storing the value of 12 in a variable of type Enums
in your case is entirely legal:
var e = (Enums) 12;
var i = (int) e; // i is 12
Therefore, Enum.TryParse
must be able to parse any value of type int
(or whichever underlying integer type used in your enumeration).
If you want to reject values having no representation in your enumeration, check them with Enum.IsDefined
.
This method strictly parses integers to the range of the enum:
public static bool EnumTryParseStrict<TEnum>(string val, out TEnum enumVal, bool ignoreCase = false) where TEnum : struct {
return Enum.TryParse(val, ignoreCase, out enumVal) && Enum.IsDefined(typeof(TEnum), enumVal);
}