There's lots of questions on here about converting strings to an enum value. Generally, the answer looks something like the answers on this question:
StatusEnum MyStatus = (StatusEnum) Enum.Parse( typeof(StatusEnum), "Active", true );
While that's a perfectly reasonable answer, and you can write a method to simplify the call, it doesn't answer the question of why Enum.Parse() returns an object
instead of the appropriate enum value. Why do I have to cast it to StatusEnum
?
Edit:
Basically, the question is why is a function like this not part of the Enum class?
public static T Parse<T>(string value) where T: struct
{
return (T)Enum.Parse(typeof (T), value);
}
This function works perfectly fine, does exactly what you'd expect. StatusEnum e = Enum.Parse<StatusEnum>("Active");
.
Parse( typeof(StatusEnum), "Active", true ); While that's a perfectly reasonable answer, and you can write a method to simplify the call, it doesn't answer the question of why Enum. Parse() returns an object instead of the appropriate enum value.
Parse(Type, String) Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.
IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.
It does this because
As such, Object
is the only type that will always work for any type of enum
.
By returning object, the API is at least functional, even if a cast is required.
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