views:

23

answers:

1

let there be:

Expression<Func<Customer, bool>> expression = c => c.Name == "John";

now i get the value by using :

string myvalue = ((ConstantExpression) bin.Right).Value;

now let there be:

string x = "John";
Expression<Func<Customer, bool>> expression = c => c.Name == x;

now i understand that

string myvalue = ((ConstantExpression) bin.Right).Value;

would generate an error because the bin.right here is not constantexpression its a field expression but the question is how do i get the value(John) out of this ?

+1  A: 

You could wrap the expression in a lambda and then compile and evaluate it. That would give you the value no matter what kind of expression it is.

string myvalue = Expression.Lambda<Func<string>>(bin.Right).Compile().Invoke();

Note that this won't work if the parameter c is used on the right hand side of the expression, since it wouldn't be defined. Also note that this will give you the current value of the right hand side when you call Invoke, and subsequent calls could return different values if the field in the object changes.


Update: If you don't know the type of the right hand side at compile time, you can use object, but this will break for value types like int. You will need to use Expression.Convert to force value types to be boxed before returning them. This will work for both value types and reference types:

object myvalue = Expression.Lambda<Func<object>>(
    Expression.Convert(bin.Right, typeof(object))).Compile().Invoke();

You could also use an untyped lambda and DynamicInvoke:

object myvalue = Expression.Lambda(bin.Right).Compile().DynamicInvoke();
Quartermeister
nice but now i have to find away to access the type of it cause ofcource its func<Object> so i cant cast int to object for some reason so if im returning int and i put Object in func it would give compile time error
Stacker
awesome , thank you so much that made it , as you can see from my other questions i have been trying to learn expressiontrees for awhile , the bad thing is i cant find a good resources about it
Stacker
nice edit Quartermeister , can i ask you for a reference to develop my knowledges in expression trees like a book or a site ?thank you so much
Stacker