Question

I am trying to instantiate a type using Activator's reflection magic. Unfortunately the type I want to instantiate has a params parameter of type object. See this extract:

public class Foo
{
    public Foo(string name, params object[] arguments)
    {
    }
}

And the instantiation goes here:

public static class Bar
{
    public static object Create(params object[] arguments)
    {
        return Activator.CreateInstance(typeof(Foo), "foo", arguments);
    }
}

Now, this effectively results in a constructor call with the signature

new Foo(string, object[])

because object[] is also object.

What I actually want is:

new Foo(string, object, object, object, ...)

Is this even possible with Activator? Or how do I instantiate a type with such a parameter type?

Was it helpful?

Solution

params is a purely-compile-time syntactic sugar.
The runtime, including the parameter binding used by reflection, ignores it.

You need to pass a normal array, just like a non-params parameter.

In your case, it sounds like you're trying to not call the params overload.

You need to build a single (flattened) array containing all of the parameters you want to pass:

object[] args = new object[arguments.Length + 1];
args[0] = "foo";
arguments.CopyTo(args, 1);

OTHER TIPS

You can pass parameters like this:

return Activator.CreateInstance(
    typeof(Foo),
    new object[] { "foo" }.Concat(arguments).ToArray());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top