Set property on a derived class of List<T> instantiated at runtime using reflection


I am using reflection to instantiate a custom class `class MyList : MyBaseClass, IList´:

foreach (FieldInfo field in this.GetType().GetFields())
   if (field.FieldType.IsGenericType && field.FieldType.GetGenericTypeDefinition() == typeof(MyList<>))
      var elementType = field.FieldType.GetGenericArguments()[0];
      var listType = typeof(MyList<>).MakeGenericType(elementType);
      var valueToSet= Activator.CreateInstance(listType);
      field.SetValue(this, valueToSet);
      valueToSet.MyName = field.Name; // does not work because "valueToSet" does not recognize this property

The problem is, that the part valueToSet.MyName = field.Name does not recognize the property MyName that my custom class MyList<T> has. I also tried defining my MyList<T> as class MyList<dynamic> : MyBaseClass, IList<dynamic> but the valueToSet.MyName = field.Name part throws now the error System.ArgumentException HResult=0x80070057 Message=Object of type objects.MyList 1[System.Object] cannot be converted to type objects.MyList 1[MyNameSpace.MyObjectType1]...

Any hint on how to resolve this? I would like to keep my original declaration without dynamics
Thanks in advance!

asked on Stack Overflow Jan 12, 2020 by (unknown user) • edited Jan 12, 2020 by Clemens

1 Answer


There are a few ways. You can choose the one that you think is the most suitable for you.

Keep using reflection

PropertyInfo myNameProperty = listType.GetProperty("MyName");
myNameProperty.SetValue(valueToSet, field.Name);

Use dynamic:

dynamic valueToSet= Activator.CreateInstance(listType);
valueToSet.MyName = field.Name;

Cast to superclass

And apparently, as you said in your comments, you can declare MyName in MyBaseClass. This is an unusual thing to be able to do, but okay... Given that MyName is declared in MyBaseClass, you can cast valueToSet to MyBaseClass:

((MyBaseClass)valueToSet).MyName = field.Name;
answered on Stack Overflow Jan 12, 2020 by Sweeper

User contributions licensed under CC BY-SA 3.0