Build expression trees to represent if-else

c# expression-trees

Question

Deserializing of Expression tree using ExpressionSerialization on a full conditional expression i.e ternary operator is giving error . If i am using ternary operator it causes FullConditionExpression (System Not Supported Exception)

Using code from following links:

http://archive.msdn.microsoft.com/exprserialization

Are there any latest version available for the above link?

http://metalinq.codeplex.com/

Tried this afterwards

public Expression<Func<object, string>> LabelCriteria { get; set; }

LabelCriteria = x =>
    {
      if (true)
          return "Cash";
      else      
          return " ";
    }

Expression doesn't support if - else block . It gives error as " A lambda expression with a statement body cannot be converted to expression tree . Is there any other way to do it.

Accepted Answer

You could use a method like here:

string myFunction(Object obj){
     //here your if-else...
}

LabelCriteria = x => myFunction(x);

Popular Answer

You must use the conditional operator:

LabelCriteria = x => true ? "Cash" : " ";

It may be that the compiler is modifying the expression because of constant folding, however, since the condition is a constant expression (true). Try using a variable there and see what happens.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why