Geeks With Blogs
Jonas Bush

Hey there!

So recently I was struggling with something for the new job, and was able to figure it out, and thought I'd share it with you, dear readers.

I have a generic class I use for parsing data. Inside that class, I ran across the need to create another instance of the generic class to parse more data, but I didn't know the type at compile time.

So I have this class:

public class MyClass<T> where T: class
    public void DoSomething() { }

In the course of DoSomething, I need to create a new MyClass, so I do that as follows:

Type classType = typeof(MyClass<>);
Type myType = classType.MakeGenericType(new Type[1] { someOtherType });
var obj = Activator.CreateInstance(myType, null);

So now I have an object "obj" that is a generic of type "someOtherType". Now to call the method!

MethodInfo mi = classType.GetMethod("DoSomething");
mi.Invoke(obj, null); // ERROR!


Uhoh! We got an error.

"System.InvalidOperationException: Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true."

I'm not 100% sure what that means, but I took a guess that because my reflected MethodInfo was off of the base generic type, not the new type I created. So I replaced the above with:

MethodInfo mi = myType.GetMethod("DoSomething");
mi.Invoke(obj, null); //SUCCESS!


And we're all good! Hope this helps you out at some point.

Posted on Thursday, July 15, 2010 3:45 PM .Net | Back to top

Comments on this post: Creating generic classes at runtime

# re: Creating generic classes at runtime
Requesting Gravatar...

Many thnx for this post.

Just this noon I was dealing with exactly the same issue. (the exception u got and the reason why u got it)

I needed to make a sweep over all my business classes through reflection, invoking the same method on each of them. But some classes were custom generic collections and they had already lead me on a bumpy road untill i got a flat tire on his one. Could have looked and searched for days since i just didn't see the problem.

But your post was an exellent spare which finally got me through to the finish line. It's often the simpel mistakes we (or just me) don't see.

Left by Bender on Dec 23, 2010 7:16 AM

Your comment:
 (will show your gravatar)

Copyright © Jonas Bush | Powered by: