Why does Enum.Parse() return object?

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.


.NET Core 2.0-3.1 and .NET 5 both support Enum.Parse like you want it


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 a FooEnum 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 writing Enum.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.

Tags:

C#

Enums