KingKerosin KingKerosin - 1 month ago 7
C# Question

Execute/Invoke ConditionalExpression to decided if to use true- or false part

I want to have the possibility to build the propertyname-chain from a given expression. I've taken the source for the conversation from here (link).

This works pretty well when used as described there.

My problem now is when I'm passing an conditional expression, e.g.


Foo((MyClass c) => createChain ? c.SomeProperty : null);


whereas
createChain
is a
bool
and inside the
Foo
the first check is for an
expr != null
to go further.

However,
expr.Body.NodeType
is now
ExpressionType.Conditional
and I don't find the right way to execute/invoke the expression so I know which part (true or false) of the expression I should set for
me
.

I've added
case ExpressionType.Conditional:
and casted
var ce = expr as ConditionalExpression
. How can I get the correct expression to be used for
me
from
ce
as one is the
c.SomeProperty
whereas the other one would be
null
depending on the value of
createChain
.

case ExpressionType.Conditional:
var ce = expr.Body as ConditionalExpression;
me = (MemberExpression) (ce != null && /*ce.Invoke()*/ ? ce.IfTrue : ce.IfFalse); // here i need to know if to use true or false part of expr
break;

Answer

Try this:

            case ExpressionType.Conditional:
                var ce = expr.Body as ConditionalExpression;
                var cond = (MemberExpression)ce.Test;
                me = (MemberExpression) (ce != null && (bool)(Expression.Lambda(cond).Compile().DynamicInvoke()) ? ce.IfTrue : ce.IfFalse); 
                break;