Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to create instance w/ generic types w/ Activator.CreateInstance?

Status
Not open for further replies.

dCyphr

Programmer
Jan 17, 2008
8
0
0
US
I have a class that has a generic type and I'm trying to create an instance using the activator but having trouble with it. This is what I have:

public abstract class MyBaseClass<T> where T : new()
{
...
public abstract T DoSomething();
}

public class MyClass<T> : MyBaseClass<T> where T : new()
{
...
public override T DoSomething() { .. }
}

And this is what I'm trying to do but didn't work. This gives my a null error: System.ArgumentNullException: Value cannot be null:

string someStr = "MyClass";
MyBaseClass<Customer> customerProvider =
Activator.CreateInstance(Type.GetType(someStr));



I also tried this but didn't work. It gave a compiler error about Activator.CreateInstance can't find that overloaded method. :

string someStr = "MyClass";
MyBaseClass<Customer> customerProvider =
Activator.CreateInstance<Customer>(Type.GetType(someStr));

Any other ideas on how to pass <Customer> to the Activator? There's gotta be some kind of syntax for it but couldn't find it anywhere.
 
Just to add to my original post, I even tried hardcoding everything like this and still gave me a null exception:

MyBaseClass<Customer> customerProvider =
Activator.CreateInstance("MyClass<Customer>");

And just to make sure I wasn't doing anything stupid somewhere, doing this worked fine:
MyBaseClass<Customer> customerProvider = new MyClass<Customer>();

Any idea on how to achieve this?
 
I got it! Phew did I have to dig.

It has very weird syntax with a backtick and brackets. Initially I tried following the MSDN guide on GetType (two-thirds down the page: which told me to do the following but still came up with a null:
Type constructedType = Type.GetType("MyClass`1[Customer]");

So in the end, this finally worked for me:
Type classType = Type.GetType("MyClass`1");
Type[] typeParams = new Type[] { typeof(Customer) };
Type constructedType = classType.MakeGenericType(typeParams);

MyBaseClass<Customer> customerProvider =
Activator.CreateInstance(constructedType) as MyBaseClass<Customer>;

I didn't realize the null was happening at GetType.. the whole time I thought the problem was with Activator.CreateInstance.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top