Search code examples
c#listgeneric-list

c# Create generic list dynamically at runtime


Following the example on this post, I found out how to create a list of generic types dynamically. Now, my issue is that I want to ADD items to the created list from an unknown source list - is there some way to achieve this?

EDIT I start with a source list containing business objects, but I absolutely need the right type of my output list, because of downstream bindings that require it.

My non-compiling code is as follows:

IList<object> sourceList; // some list containing custom objects
Type t = typeof(IList).MakeGenericType(sourceList[0].GetType());
IList res = (IList)Activator.CreateInstance(t);
foreach (var item in sourceList) {
    reportDS.Add(item); // obviously does not compile
}

Solution

  • I would recommend moving your code into a generic class or function, moving the reflection to a higher level:

    private static List<T> CloneListAs<T>(IList<object> source)
    {
        // Here we can do anything we want with T
        // T == source[0].GetType()
        return source.Cast<T>().ToList();
    }
    

    To call it:

    IList<object> sourceList; // some list containing custom objects
    // sourceList = ...
    
    MethodInfo method = typeof(this).GetMethod("CloneListAs");
    MethodInfo genericMethod = method.MakeGenericMethod(sourceList[0].GetType());
    
    var reportDS = genericMethod.Invoke(null, new[] {sourceList});