Jonas Bush

Blog.blog.blog.blog
posts - 16, comments - 166, trackbacks - 17

My Links

News

Archives

Post Categories

Image Galleries

General

Thursday, July 15, 2010

Creating generic classes at runtime

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 | Feedback (1) | Filed Under [ .Net ]

Powered by: