Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a value of a reference type in an Expression?

Tags:

c#

.net

lambda

I have this method:

public void DoSomething<T>(Expression<Func<T, object>> method)
{
}

If this method is called like this:

DoSomething(c => c.SomeMethod(new TestObject()));

... how do I get the value of the parameter that was passed into SomeMethod()?

If the parameter is a value type, this works:

var methodCall = (MethodCallExpression)method.Body;
var parameterValue = ((ConstantExpression)methodCall.Arguments[0]).Value;

However, when I pass in a reference type, methodCall.Arguments[0] is a MemberExpression, and I can't seem to figure out how to write code to get the value out of it.

like image 708
Jon Kruger Avatar asked Dec 29 '22 22:12

Jon Kruger


1 Answers

Here is the answer (inspired by Akash's answer):

LambdaExpression lambda = Expression.Lambda(methodCall.Arguments[0]);
var compiledExpression = lambda.Compile();
return compiledExpression.DynamicInvoke();
like image 78
Jon Kruger Avatar answered Dec 31 '22 10:12

Jon Kruger