Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Enum.Parse() return object?

Tags:

c#

enums

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");.

like image 820
Bobson Avatar asked Sep 07 '12 20:09

Bobson


People also ask

Why does enum Parse return object?

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.

What does enum Parse do?

Parse(Type, String) Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

Can you cast a string to an enum?

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.


1 Answers

It does this because

  1. It predated generics and (even if it hadn't:)
  2. Generic constraints can't be enums (in the mainstream .NET languages)

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.

like image 173
Reed Copsey Avatar answered Sep 23 '22 19:09

Reed Copsey