Using a Type object to create a generic

Posted by Richard Neil Ilagan on Stack Overflow See other posts from Stack Overflow or by Richard Neil Ilagan
Published on 2010-03-29T20:50:14Z Indexed on 2010/03/29 20:53 UTC
Read the original article Hit count: 223

Filed under:
|
|
|

Hello all! 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! ^_^

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics