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");
.
A solution could be to use a static extension method.
It does this because
As such,
Object
is the only type that will always work for any type ofenum
.By returning object, the API is at least functional, even if a cast is required.
TryParse does however support a type parameter:
Enum.TryParse<FooEnum>(name, true, out ret);
Therefore, if you specify the out value ret as
FooEnum ret;
, you won't need to cast it to aFooEnum
afterwards; it'll be of the proper type right away.The actual type of the object is indeed
StatusEnum
. The compiler, and the code, when writingEnum.Parse
has no idea what that runtime object will be at the time the method is written. It won't be known until the method is actually called.