Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create generic List<T> with reflection

Tags:

c#

reflection

I have a class with a property IEnumerable<T>. How do I make a generic method that creates a new List<T> and assigns that property?

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

I dont know where is T type can be anything

like image 426
rkmax Avatar asked Feb 15 '13 04:02

rkmax


1 Answers

Assuming you know the property name, and you know it is an IEnumerable<T> then this function will set it to a list of corresponding 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);
}

Please note this method does no type checking, or error handling. I leave that as an exercise to the user.

like image 156
Josh Avatar answered Nov 12 '22 20:11

Josh