2

There is a method defined like so:

public static void MyMethod(Delegate action, parames object[] parameters)
{
   action.DynamicInvoke(parameters);
   //Do something
}

So far this method works very well to receive all kinds of method and functions with any number of parameters but I was wondering if there is a way to pass a constructor as the Delegate parameter.

Thank you for your help.

Sergio Romero
  • 6,477
  • 11
  • 41
  • 71

2 Answers2

8

You will have to construct an anonymous function around the constructor, as constructors cannot be converted to delegates directly. (This is because the constructor is not what actually creates an object; the newobj instruction creates the object and then calls the constructor to initialize the allocated memory. Creating a delegate for a constructor directly would be the equivalent of a call instruction, and that doesn't make sense for constructors.)

For example, given this type:

class Foo {
    public Foo(string str) { }
}

You could do this:

MyMethod(new Func<string, Foo>(str => new Foo(str)), "a string");
Sergio Romero
  • 6,477
  • 11
  • 41
  • 71
cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • 1
    +1 for a fantastic answer that leverages the current method. I was pretty sure the only way was `Activator.CreateInstance`. – Mike Perrenoud Apr 04 '13 at 17:07
  • @cdhowie: It does not seem to like it. I am trying it with MyMethod((x, y) => new MyObject(x, y), objectOne, objectTwo) and the compiler says "Argument type 'lambda expression' is not assignable to parameter type 'System.Delegate' – Sergio Romero Apr 04 '13 at 17:31
  • @cdhowie: I took the liberty of making a very small correction to the answer and that makes it exactly what I was looking for. Thank you! – Sergio Romero Apr 04 '13 at 20:50
1

As cdhowie showed you, it is possible with your current method, but another option if necessary is to leverage Activator.CreateInstance, so it might look something like this:

public static object CreateObject(Type t, params object[] parameters)
{
    return Activator.CreateInstance(t, parameters);
}
Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232