Dynamically generate an Action

.net c# expression-trees


I'm trying to work out how to dynamically create an Action at runtime but coming up short.

Let's say I want to call a method and pass in a dynamically created Action so I can track whether the Action has been invoked etc (for whatever reason).

void DoSomething(Action<string> action);

That's the method I'm going to invoke and I want to somehow dynamically build an Action that'll satisfy the parameter.

I know I could just build one using new Action<string>((s) => { });

But for this case I don't know at compile-time the signature of the Action and all I want is a super-generic Action that'll let me know if it's been invoked.

This is part of a communication system for a project and I want to be able to support Actions being usable (think an OnCompleted callback).

Proxy.DoSomething((s) => Console.WriteLine("The server said: " + s);

I want to be able to generate a representation, shoot that over the wire, create an Action dynamically on the server, invoke the method on the object and pass in my dynamic action, send the result back to the client and invoke the actual action there.

A little clarification:

Client Side:

var proxy = GetProxyObject(); // Comms proxy
proxy.DoSomething((reply) => Console.WriteLine("Server said: " + reply));


  1. Discover the signature of the Action
  2. Build an internal representation object (easy enough)
  3. Send that over the wire to the server

Server Side:

void ReceivedMessage(msg)
   var actParam = msg.Parameters[0]; // This is obviously just for demonstration
   var action = BuildActionWrapper(actParam);
   var result = target.InvokeMethod("DoSomething", action.UnderlyingAction);

   // Send result and Action result back to client

void DoSomething(Action<string> act)

Then back on the client side the parameters passed into the dynamically generated action on the server, the real action just gets invoked with those.

2/18/2013 9:07:35 AM

Accepted Answer


So I've appeared to solve the problem to a degree, it's nasty and probably quite a way from how it should look.

    var mi = this.GetType().GetMethod("DoSomething");
    var actArg = mi.GetParameters()[0];
    var args = actArg.ParameterType.GenericTypeArguments;

    var lt = Expression.Label();

    List<object> values = new List<object>();

    var valVar = Expression.Variable(typeof(List<object>), "vals");
    var para = args.Select(a => Expression.Parameter(a))

    var setters = new List<Expression>();

    foreach (var p in para)
            typeof(List<object>).GetMethod("Add", new[] { typeof(object) }), p));

    var block = Expression.Block(
        variables: new ParameterExpression[]

        expressions: Enumerable.Concat(para,
        new Expression[]
            Expression.Assign(valVar, Expression.Constant(values)),
        .Concat(new Expression[]
    var l = Expression.Lambda(block, para).Compile();
    mi.Invoke(this, new object[] { l });

Basically, this builds a list to hold all the Action parameters the method sets in:

public void DoSomething(Action<string> act)

The parameters of the expression are built using the type arguments of the action and a number of setter expressions are built to add that particular parameter into the value list.

When run the expression assigns the values list as a constant to a variable it has, the setter expressions then add their values into the list and the expression returns.

The net result is that any Action can have an action dynamically generated and the results just chucked into a list, the list could then be sent across the wire from server to client and the values would be used on the client as the arguments to the actual action.

2/18/2013 10:54:35 AM

Popular Answer

Here's an example of how you could build such an expression tree:

var mi = typeof(Console).GetMethod("WriteLine", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(string) }, null);
var parameter = Expression.Parameter(typeof(string));
var body = Expression.Call(null, mi, new[] { parameter });
Expression<Action<string>> expression = Expression.Lambda<Action<string>>(body, new[] { parameter });


As an alternative you could use Reflection.Emit to generate a delegate at runtime.

For example:

var dynMethod = new DynamicMethod("", null, new[] { typeof(string) });
var il = dynMethod.GetILGenerator();
var mi = typeof(Console).GetMethod("WriteLine", BindingFlags.Public | BindingFlags.Static, null, new[] { typeof(string) }, null);
il.Emit(OpCodes.Call, mi);

var dynDelegate = (Action<string>)dynMethod.CreateDelegate(typeof(Action<string>));

This will generate the following delegate:

(string s) => Console.WriteLine(s)

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow