a constructor as a delegate - is it possible in C#?

Viewed 25318

I have a class like below:

class Foo
{
  public Foo(int x) { ... }
}

and I need to pass to a certain method a delegate like this:

delegate Foo FooGenerator(int x);

Is it possible to pass the constructor directly as a FooGenerator value, without having to type:

delegate(int x) { return new Foo(x); }

?

EDIT: For my personal use, the question refers to .NET 2.0, but hints/responses for 3.0+ are welcome as well.

9 Answers

Another option would be to use the Activator class, like so:

Using Generic Types

public delegate Foo FooGeneratorDelegate<T>(int x);

public T FooGeneratorFunction<T>(int x)
{
    return (T)Activator.CreateInstance(typeof(T), x);
}

// implementation example
FooGeneratorDelegate<Foo> del = FooGeneratorFunction<Foo>;
Foo foo = del(someIntValue);

Passing Your Type Foo as a Parameter

public delegate object FooGeneratorDelegate(Type t, int x);

public object FooGeneratorFunction(Type t, int x)
{
    return Activator.CreateInstance(t, x);
}

// implementation example
FooGeneratorDelegate del = FooGeneratorFunction;
Foo foo = (Foo)del(typeof(Foo), someIntValue);

If the Type will Always be of Type Foo

public delegate Foo FooGeneratorDelegate(int x);

public Foo FooGeneratorFunction(int x)
{
    return (Foo)Activator.CreateInstance(typeof(Foo), x);
}

// implementation example
FooGeneratorDelegate del = FooGeneratorFunction;
Foo foo = del(someIntValue);

While other answers only support parameter-less constructor. Here is the version support parameters. Hope it can help someone who want to turn with-parameters ConsturctorInfo to Delegate.

public Delegate CreateDelegate(ConstructorInfo constructorInfo)
{
    var ctorParameters = constructorInfo.GetParameters();
    var lambdaParameters =
        ctorParameters.Select(x => Expression.Parameter(x.ParameterType, x.Name)).ToArray();
    var argsExp =
        ctorParameters.Select((p, i) => Expression.Convert(lambdaParameters[i], p.ParameterType));
    var newExp = Expression.New(constructorInfo, argsExp);
    var lambda = Expression.Lambda(newExp, lambdaParameters);
    return lambda.Compile();
}

Usage:

CreateDelegate(/* ConstructorInfo */).DynamicInvoke(args);
Related