This question already has an answer here:
-
How to dynamically create generic C# object using reflection? [duplicate]
5 answers
I have an object as a parameter and I want to make a generic list out of that object type. Most of times I want to send a custom object type. This code declares the concept of my problem.
public void myMethod(object myObject)
{
List<typeof(myObject)> _NewList=new List<typeof(myObject)();
}
You could make the method generic:
public void myMethod<T>(T myObject)
{
List<T> _NewList = new List<T>();
}
You can constrain the type to an interface or base class if your method needs to execute anything consistent on these objects.
Via reflection:
var type = myObject.GetType();
var genericListType = typeof(List<>).MakeGenericType(new[] { type });
var list = (IList)Activator.CreateInstance(genericListType);
But it would be better to use generics.