Let's say I have this ctor:
public MyType<T>(int myInt, string myString, params T[] myObjects) { }
I could set the params array itself to null
(rather than pass a null into the array):
MyType(1, "foo", (T[])null)
Let's say I want to do that dynamically. I tried this:
var args = new object[] { 1, "foo", null };
var myType = Activator.CreateInstance(typeof(MyType), BindingFlags.Instance | BindingFlags.NonPublic, null, args, null);
But that throws a MissingMethodException
.
If I change the ctor's params T[]
to params object[]
then it works, but I prefer to keep the generic form.
How can I do this?
Activator.CreateInstance
seems kind of a convience wrapper round Type.GetConstructor
. The latter has the advantage that you can specify the ctor's signature explicitly, which will help you out in this case:
//usage:
var intItem = CreateGeneric<int> (1, "int_str", null);
var strItem = CreateGeneric<string> (2, "str_str", null);
public static MyType<T> CreateGeneric<T>(int myInt, string myString, T[] array)
{
//specify c'tor signature and get ctor-info
var types = new [] { typeof(int), typeof(string), typeof(T[])};
var ctor = typeof(MyType<T>).GetConstructor(
BindingFlags.Instance | BindingFlags.NonPublic, null, types, null);
//create instance
var args = new object[] { myInt, myString, array };
var instance = (MyType<T>)ctor.Invoke(args);
return instance;
}
Full demo: https://dotnetfiddle.net/h3lpZc