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 work
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:
public class Program
{
public struct MyType
{
public ICollection MyProperty { get; set; }
}
static void Main(string[] args)
{
var type = typeof(MyType);
var properties = type.GetProperties();
var destProperty = properties[0];
var genericTypeDefinition = destProperty.PropertyType.GetGenericTypeDefinition();
var madeGenericType = genericTypeDefinition.MakeGenericType(destProperty.PropertyType.GetGenericArguments());
var ctor = madeGenericType.GetConstructor(Type.EmptyTypes);
}
}
If you put a breakpoint on the penultimate brace you'll see that ctor comes back as null, which is because, as you correctly surmised, ICollection 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 to use in this situation". You'll need to make that decision and new one, based on the information you get back from reflection.