class Program
{
static void Main(string[] args)
{
string value = "12345";
Type enumType = typeof(Fruits);
Fruits fruit = Fruits.Apple;
try
{
fruit = (Fruits) Enum.Parse(enumType, value);
}
catch (ArgumentException)
{
Console.WriteLine(String.Format("{0} is no healthy food.", value));
}
Console.WriteLine(String.Format("You should eat at least one {0} per day.", fruit));
Console.ReadKey();
}
public enum Fruits
{
Apple,
Banana,
Orange
}
}
If you execute the code above the result shows:
You should eat at least one 12345 per day.
I really expected an ArgumentException to be thrown if a unknown name (string) is passed. Taking a close look at the Enum.Parse definition reveals:
Summary:
Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.Exceptions:
ArgumentException: enumType is not an Enum. -or- value is either an empty string or only contains white space. -or- value is a name, but not one of the named constants defined for the enumeration.
I.e. if a string representation of an integer is passed, a new enum value is created and now exception is thrown by design. Does this make sense?
At least I now know to call Enum.IsDefined(enumType, value) prior to Enum.Parse()
The “named constant” is the textual representation of an Enum’s value, not the number that you’ve assigned to it.
If you change:
To:
You’ll see the error you’re expecting, because “value is a name, but not one of the named constants defined for the enumeration.”. In this instance the value you’re passing in is a name, “Cake”, but not one in the enumeration.
Think of
Enum.Parse(enumType, value);doing the following:valueis a null reference, throw an ArgumentNullExceptionvalueone of the named constants in the enumeration inenumType. If yes, return that value from the enumeration and stop.valuedirectly convertible to the underlying type (in this instance Int32), if yes, return that value and stop (even if there’s no named constant for that value).valuedirectly convertible to the underlying type, but outside of the range of the underlying type? e.g. the value is a string containing a number one greater than MAXINT. If yes, throw anOverflowException.