Reputation: 21
I want to create method that in argument will take Type an use it as type of generic list for example:
MyClass something = new MyClass();
Type myType = something.GetType();
public void createList(Type type)
{
List<type> myList = new List<type>(); // <-- How can I achieve that?
...
}
Any ideas? :)
Upvotes: 0
Views: 39
Reputation: 149068
Start off by making your core method generic, like this:
public void createList<T>()
{
List<T> myList = new List<T>();
...
}
And provide a non-generic overload which uses reflection to dynamically invoke the generic method:
public void createList(Type t)
{
this.GetType()
.GetMethod("createList", Type.EmptyTypes)
.MakeGenericMethod(t)
.Invoke(this, null);
}
Upvotes: 1