Create a shared list <T> with reflection

I have a class with a property IEnumerable<T>. How to create a general method that creates a new one List<T>and assigns this property?

IList list = property.PropertyType.GetGenericTypeDefinition()
    .MakeGenericType(property.PropertyType.GetGenericArguments())
    .GetConstructor(Type.EmptyTypes);

I don't know where type T could be anything

+5
source share
2 answers

Assuming you know the name of the property, and know what it is IEnumerable<T>, then this function will set it to a list of the appropriate type:

public void AssignListProperty(Object obj, String propName)
{
  var prop = obj.GetType().GetProperty(propName);
  var listType = typeof(List<>);
  var genericArgs = prop.PropertyType.GetGenericArguments();
  var concreteType = listType.MakeGenericType(genericArgs);
  var newList = Activator.CreateInstance(concreteType);
  prop.SetValue(obj, newList);
}

Note that this method does not check for type or error handling. I leave this as an exercise for the user.

+16
source
using System;
using System.Collections.Generic;

namespace ConsoleApplication16
{
    class Program
    {
        static IEnumerable<int> Func()
        {
            yield return 1;
            yield return 2;
            yield return 3;
        }

        static List<int> MakeList()
        {
            return (List<int>)Activator.CreateInstance(typeof(List<int>), Func());
        }

        static void Main(string[] args)
        {
            foreach(int i in MakeList())
            {
                Console.WriteLine(i);
            }
        }
    }
}
+1
source

All Articles