Sergio Romero
Sergio Romero

Reputation: 6597

In C# use the Delegate class to invoke a constructor

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.

Upvotes: 2

Views: 3559

Answers (2)

cdhowie
cdhowie

Reputation: 168998

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");

Upvotes: 8

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

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);
}

Upvotes: 1

Related Questions