Andrew Bullock
Andrew Bullock

Reputation: 37378

How to get value of constantexpression

I'm trying to evaluate the value of a constant expression. In the debugger I can see the value:

watch

but how do I get at it in code?

The expression is of the form:

x => x.ListPropery[5].ChildProperty

I'm walking down the expression to convert it into a string, but I've got stuck at the indexer part.

The indexer creates a MethodCallExpression on IList<> to get_Item, I can then work my way into the arguments to get at a constant expression which was generated like this:

for(var i = 0; i < list.Count; i++)
{
    var j = i;
    Expression<Func<IList<TValue>, TValue>> indexer = xs => xs[j];

Update:

(exp.Arguments[0] as MemberExpression).Member

returns a MemberInfo

Upvotes: 2

Views: 2034

Answers (4)

Dawid Mostert
Dawid Mostert

Reputation: 123

You can also try the following:

LambdaExpression lambda = Expression.Lambda(exp.Arguments[0]);
var val = lambda.Compile().DynamicInvoke();

Upvotes: 5

Marco
Marco

Reputation: 47

right click the Name of the expression in the debugger choose 'add watch' then copy the name into your code.

Upvotes: -3

Arthur
Arthur

Reputation: 8129

There is a great article series about bulding a LinqProvider.

http://blogs.msdn.com/b/mattwar/archive/2008/11/18/linq-links.aspx

In this Part there is an Evaluator which identifies constant expressions

http://blogs.msdn.com/b/mattwar/archive/2007/08/01/linq-building-an-iqueryable-provider-part-iii.aspx

I've used it sucessfully.

Upvotes: 2

Andrew Bullock
Andrew Bullock

Reputation: 37378

aha!

(exp.Arguments[0] as MemberExpression).Member is a FieldInfo

so I can do:

((exp.Arguments[0] as MemberExpression).Member as FieldInfo).GetValue(((exp.Arguments[0] as MemberExpression).Expression as ConstantExpression).Value)

Upvotes: 4

Related Questions