Geeks With Blogs
Marcin Celej blog

I had a problem some time ago. I needed to create generic type object dynamically. I couldn't find how to do it. Now, when I know, I can share the mysterious knowledge.

public static object CreateGeneric(Type generic, Type innerType, params object[] args)
{
	System.Type specificType = generic.MakeGenericType(new System.Type[] { innerType });
	return Activator.CreateInstance(specificType, args);
}

To create a genric List of string, use the following code:

CreateGeneric(typeof(List<>), typeof(string));

If the generic type constructor requires parameters, they can be passed to the CreateGeneric method.

The CreateGeneric method supports only one generic argument but it can be easily modified to support more (e.g. creation of Dictionary<T, U>)

Posted on Saturday, March 24, 2007 10:46 PM | Back to top


Comments on this post: Creating generic type object dynamically using reflection

# re: Creating generic type object dynamically using reflection
Requesting Gravatar...
Very useful, thanks!

Had read somewhere that creating generic types on-the-fly with having a "T" to use was a pain, but your sample it pretty simple.

Production code here we come!
Left by Simon Stewart on Jul 22, 2007 8:37 PM

# re: Creating generic type object dynamically using reflection
Requesting Gravatar...
It is not working for System.Nullable<int>. The object created is an int, not a "new Nullable<int>(int)".

I am currently working on it.
Left by Jason White on Aug 12, 2007 10:03 AM

# re: Creating generic type object dynamically using reflection
Requesting Gravatar...
Thank you Very much..
Left by Mohamed Bakr on Jan 29, 2008 4:40 AM

# re: Creating generic type object dynamically using reflection
Requesting Gravatar...
So.. if you created your List<T> object from your method how could you then pull out specific indexes etc. from the object returned?

So for example..

Object o = CreateGeneric(typeof(List<>), typeof(string));
string 1 = o[0];// ??
Left by Justin on Mar 03, 2008 6:10 AM

# re: Creating generic type object dynamically using reflection
Requesting Gravatar...
You have two choices:

1. Cast the created object
2. Use reflection to access the indexer

The choice is yours.
Left by Marcin Celej on Mar 03, 2008 8:00 AM

# re: Creating generic type object dynamically using reflection
Requesting Gravatar...
thank you, this was a ncie code snippet to find. What do you think of the following approach - I think it's a little more concise and eliminate the need to cast from object to your specific type since you define the type in the create call...

public static T CreateGeneric<T>(params object[] args)
{
Type generic = typeof(T);
return (T)Activator.CreateInstance(generic, args);
}

list = CreateGeneric<List<string>>(null);

Left by Shannon Richards on Oct 05, 2008 6:38 AM

# re: Creating generic type object dynamically using reflection
Requesting Gravatar...
Hi, it actually doesn't have a sense to create a generic method that creates generic type dynamically as you can just create it in your code. Let me explain this:

If you can call CreateGeneric<List<string>>() in your code than you can with the same effort write new List<string>(null)

I hope it explains it well. I used a sample "CreateGeneric(typeof(List<>), typeof(string));" just to explain how it works but in such case you should not use the dynamic object creation.
Left by Marcin Celej on Oct 05, 2008 6:46 AM

# re: Creating generic type object dynamically using reflection
Requesting Gravatar...
hi

can you help me?
i have a Table, in one column , i have controls type and i want to create dynamically and set propertits, for example , tblFrame , it has column with data : Image, Panel, ...
and i want to reda type from database and create controls and set properties
my email is Fatemeh.akbari@gmail.com
best regards
Left by Fatemeh on Oct 11, 2008 7:26 PM

# re: Creating generic type object dynamically using reflection
Requesting Gravatar...
Just what I was looking for, thanks! It's so easy once you see it.
Left by Jim on Oct 27, 2008 1:33 PM

# re: Creating generic type object dynamically using reflection
Requesting Gravatar...
thanks !
Left by Igor on Jun 13, 2009 7:32 AM

# re: Creating generic type object dynamically using reflection
Requesting Gravatar...
Tks so much... This snippet save me today =D
Left by Bruno Feliciano on Jul 17, 2009 7:33 AM

# re: Creating generic type object dynamically using reflection
Requesting Gravatar...
So how can I cast the created object if I just have the type? like

private List<object> ParseModel(Type model)
{
var objectList = CreateGeneric(typeof(List<>), model);
}

Thanks in advance
Left by Nicolas Porto on Nov 25, 2009 4:02 PM

# re: Creating generic type object dynamically using reflection
Requesting Gravatar...
Unfortunatelly generics are not castable. Try doing something like this:

List<object> a = (List<object>)new List<string>();

this code will not compile. Even if you have a variable of type object (let's call it a), that holds a reference to a List<string>; you will receive InvalidCastException when you try sth like that:

List<object> a = (List<object>)a;
Left by Marcin Celej on Nov 27, 2009 8:10 AM

# re: Creating generic type object dynamically using reflection
Requesting Gravatar...
hi,
I want to create instance of a typed class whos type is keept in the web.config and when try to this I get an exception that say Could not load x from y assembly,
any solution for this
Left by reza zareian fard on Feb 24, 2010 7:48 AM

# re: Creating generic type object dynamically using reflection
Requesting Gravatar...
Hi,
I want to create an object based on type and i need to copy the data from another object.Any body help plz.......
Left by Swetha on May 17, 2010 4:20 PM

# re: Creating generic type object dynamically using reflection
Requesting Gravatar...
Wery nice snippet, pidory)
Left by Dolbotron on Jan 12, 2011 11:57 PM

# re: Creating generic type object dynamically using reflection
Requesting Gravatar...
Many thanks, saved me from working this out from scratch!
Left by Will on Apr 19, 2011 10:08 PM

# re: Creating generic type object dynamically using reflection
Requesting Gravatar...
Hey,
This is great.
My only problem is that I also need a reference to this Generic collection that I'm creating, and since I can't define the generic type I can't do it.

Using your solution I managed to call invoke a call for A<t>, but this method returns object, and I need a reference to B<t>. and since I can't create T as a generic type then I can't create a reference of it - please help :)
Left by Guy on May 12, 2011 2:04 AM

# re: Creating generic type object dynamically using reflection
Requesting Gravatar...
what if i need create generic type when parameter is also generic type, so need some recoursive making generic types?how to do this?
Thanks
Left by dmitry on Jan 25, 2012 7:57 PM

# re: Creating generic type object dynamically using reflection
Requesting Gravatar...
NICE. Many Thanks. I do not know the type of List at runtime and wish to shallow copy the list. Very hard to do, until I saw this.
Left by bk on Apr 19, 2012 10:24 AM

# re: Creating generic type object dynamically using reflection
Requesting Gravatar...
Thank you just what I was looking for I was trying to build list using type stored in a file:

public object Get(Type t)
{
Type listType = typeof(List<>).MakeGenericType(new Type[] { t });
MethodInfo method = typeof(Request).GetMethod("GetInternal", BindingFlags.Instance | BindingFlags.NonPublic);
MethodInfo genericMethod = method.MakeGenericMethod(new Type[] { listType });
return genericMethod.Invoke(this, null);
}
Left by Rick Nash on Aug 03, 2012 3:39 AM

# as usual another unit incher post worthless article
Requesting Gravatar...
hey marcin how long you had that unit incher of yours up a goats ahole
Left by marcin sucks the dick on Jul 10, 2014 2:02 AM

Your comment:
 (will show your gravatar)


Copyright © Marcin Celej | Powered by: GeeksWithBlogs.net | Join free