Akash Akash - 1 month ago 4
C# Question

Accessing calling object from MethodCallExpression

I'm trying to learn about Expression trees, and I've created a method that takes an


and executes it if it satisfies some conditions - see the code below.

private static void TryCommand(Expression<Func<bool>> expression)
var methodCallExpression = expression.Body as MethodCallExpression;
if (methodCallExpression == null)
throw new ArgumentException("expression must be a MethodCallExpression.");

if (methodCallExpression.Object.Type != typeof (MyClass))
throw new ArgumentException("expression must be operating on an instanceof MyClass.");

var func = expression.Compile();
var success = func.Invoke();

Console.WriteLine(methodCallExpression.Method.Name + "() failed with error code " + (func.Target as MyClass).GetError());

The problem that

(func.Target as MyClass)

is null. Clearly I'm doing something wrong! How do I access the instance that the method is operating on?


The target of the method call is an instance of MyClass, but the delegate itself isn't the method call. It's something which will perform the method call when it's executed.

If you look at func.Target, you'll see it's a System.Runtime.CompilerServices.ExecutionScope.

Now you could test for that, cast to it, and then fetch either the Locals or the Globals (not sure which) to get the target. However, I suspect it would be cleaner just to change to use a Func<int> (or whatever type your error code is) and return the error code when you execute the delegate in the first place. Then you wouldn't even need an expression tree.

EDIT: Given your comments, I'd suggest:

public static void TryCommand(Expression<Func<MyClass,bool>> command,
                              MyClass c)
    // Code as before to find the method name etc.

    Func<MyClass, bool> compiled = command.Compile();

    if (!compiled(c))
            + "() failed with error code " + c.GetError());

You'd then call it with:

TryCommand(x => x.SomeMethod(), myClass);