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:
string value = "12345";
To:
string value = "Cake";
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:
value
is a null reference, throw an ArgumentNullExceptionvalue
one of the named constants in the enumeration in enumType
. If yes, return that value from the enumeration and stop.value
directly 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).value
directly 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 an OverflowException
.An enum can be any value of its base integer type. It is not just restricted to named constants.
For instance, the following is perfectly valid:
enum Foo{
A,
B,
C,
D
}
Foo x = (Foo)5;
Even though 5 does not correspond to a named constant, it is still a valid value for Foo
, since the underlying type for Foo
is Int32
.
If one were to call x.ToString()
, the returned value would be simply "5", since no named constant corresponds with x's value.
Enum.Parse()
is the converse function of Enum.ToString()
. You should expect that whatever Enum.ToString()
can return that Enum.Parse()
can accept. This includes, for instance, comma-separated values for flags enums:
[Flags]
enum Foo{
A = 1,
B = 2,
C = 4,
D = 8
}
Foo x = Foo.A | Foo.B | Foo.C | Foo.D;
int i = (int)x;
string s = x.ToString();
Console.WriteLine(i);
Console.WriteLine(s);
Console.WriteLine((Foo)Enum.Parse(typeof(Foo), i.ToString()) == x);
Console.WriteLine((Foo)Enum.Parse(typeof(Foo), s) == x);
Output:
15 A, B, C, D True True
EDIT:
What you really seem to want is something like this:
static Enum GetEnumValue(Type enumType, string name){
// null-checking omitted for brevity
int index = Array.IndexOf(Enum.GetNames(enumType), name);
if(index < 0)
throw new ArgumentException("\"" + name + "\" is not a value in " + enumType, "name");
return Enum.GetValues(enumType).GetValue(index);
}
or a case-insensitive version:
static Enum GetEnumValue(Type enumType, string name, bool ignoreCase){
// null-checking omitted
int index;
if(ignoreCase)
index = Array.FindIndex(Enum.GetNames(enumType),
s => string.Compare(s, name, StringComparison.OrdinalIgnoreCase) == 0);
// or StringComparison.CurrentCultureIgnoreCase or something if you
// need to support fancy Unicode names
else index = Array.IndexOf(Enum.GetNames(enumType), name);
if(index < 0)
throw new ArgumentException("\"" + name + "\" is not a value in " + enumType, "name");
return Enum.GetValues(enumType).GetValue(index);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With