Noob
Noob

Reputation: 1049

Casting to a Generic Typed Object Using Reflection

Can I cast an object from type object to MyType<T> using reflection if I don't know what T is until runtime?

Upvotes: 3

Views: 3132

Answers (2)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112269

The trick in such situations, is to use a non-generic class with generic methods.

public class MyType
{
    public T GetResult<T>() {
    }
}

Note, however, that this happens at compile time. Generics give you the opportunity to create different "flavors" of a type or a method at compile time; but generics are not dynamic! Generics are type-safe and type safety can only be achieved at compile time (because it's the compiler who checks the type safety).

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564333

You can't cast to a type unknown at compile time. Casting is really only useful as a compile-time construct, as you'd need to know the type in order to use it directly.

If your goal is to work with the object via Reflection, however, that's a different scenario. In that case, you can use Type.MakeGenericType to create the correct type for your object.

This will allow you to use reflection to work upon your object.

Upvotes: 5

Related Questions