Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a Type object to create a generic

I'm trying to create an instance of a generic class using a Type object.

Basically, I'll have a collection of objects of varying types at runtime, and since there's no way for sure to know what types they exactly will be, I'm thinking that I'll have to use Reflection.

I was working on something like:

Type elType = Type.GetType(obj);
Type genType = typeof(GenericType<>).MakeGenericType(elType);
object obj = Activator.CreateInstance(genType);

Which is well and good. ^___^

The problem is, I'd like to access a method of my GenericType<> instance, which I can't because it's typed as an object class. I can't find a way to cast it obj into the specific GenericType<>, because that was the problem in the first place (i.e., I just can't put in something like:)

((GenericType<elType>)obj).MyMethod();

How should one go about tackling this problem?

Many thanks! ^___^

like image 318
Richard Neil Ilagan Avatar asked Mar 29 '10 20:03

Richard Neil Ilagan


2 Answers

You would have to continue using Reflection to invoke the actual method:

// Your code
Type elType = Type.GetType(obj);
Type genType = typeof(GenericType<>).MakeGenericType(elType);
object obj = Activator.CreateInstance(genType);

// To execute the method
MethodInfo method = genType.GetMethod("MyMethod",
    BindingFlags.Instance | BindingFlags.Public);
method.Invoke(obj, null);

For more information see Type.GetMethod and MethodBase.Invoke.

like image 69
Aaronaught Avatar answered Sep 30 '22 12:09

Aaronaught


Once you start the reflection game you have to play it till the end. The type is not known at compile time, so you cannot cast it. You'll have to invoke the method by reflection:

obj.GetType().InvokeMember(
    "MyMethod", 
    BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod, 
    null, 
    obj, 
    null
);
like image 22
Darin Dimitrov Avatar answered Sep 30 '22 13:09

Darin Dimitrov