0

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;
Community
  • 1
  • 1
KingKerosin
  • 3,639
  • 4
  • 38
  • 77

1 Answers1

1

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;
John M
  • 2,510
  • 6
  • 23
  • 31
  • This throws `InvalidCastException: Unable to cast object of type 'System.Linq.Expressions.FieldExpression' to type 'System.Linq.Expressions.ConstantExpression'.` – KingKerosin Oct 27 '16 at 09:34
  • Updated. Although you may still have a problem if your conditional expression evaluates to null as obviously that won't cast to a MemberExpression – John M Oct 27 '16 at 10:59
  • Thanks. Using safe casting and checking against `null` seems to do the trick for my case – KingKerosin Oct 27 '16 at 11:05
  • Line 3 throws `Unable to cast object of type System.Linq.Expressions.LogicalBinaryExpression to type System.Linq.Expressions.MemberExpression`. – IngoB Aug 10 '22 at 21:43