I have a function that uses reflection to set properties of object A from object B.
At one point, I need to instantiate a generic collection. However, I am unable to get it working. Here is what I have now:
IList list = destProperty.PropertyType.GetGenericTypeDefinition()
.MakeGenericType(destProperty.PropertyType.GetGenericArguments())
.GetConstructor(Type.EmptyTypes)
.Invoke(null) as IList;
I am trying to set the value of the destProperty. It has to be a List
At runtime, the destProperty is of type ICollection<>. I think what’s happening is that since ICollection is an interface, it has no constructor. What is the proper way to instantiate it then?
Thanks!
I’ve re-written your code, into the form of an example (hopefully that matches what you’re trying to do! =), to try and make it clearer what the problem is:
If you put a breakpoint on the penultimate brace you’ll see that
ctorcomes back asnull, which is because, as you correctly surmised,ICollection<T>doesn’t have any constructors due to it being an interface.Because of this, there’s no “super-generic” way of doing this because there’s no inherent way to say “what’s the best implementation of
ICollection<T>to use in this situation”. You’ll need to make that decision andnewone, based on the information you get back from reflection.