SoFunction
Updated on 2025-03-06

Implementation of expression tree of C# judgment statement

C# provides the following types of judgment statements:

Statement describe
if oneif statementComposed of a Boolean expression followed by one or more statements.
if...else oneif statementAdd to an optionalelse statement, the else statement is executed when the Boolean expression is false.
Nested if statements You can do it in oneiforelse ifUse another statementiforelse ifSentence.
switch statement oneswitchA statement allows testing when a variable equals multiple values.
Nested switch language You can do it in oneswitchUse another statementswitchSentence.

Of course there is???:Social judgments will be made in detail below.

if

If statement, useIfThen(Expression test, Expression ifTrue);To express

Expression testRepresents the expression used for judgment,Expression ifTrueRepresents the expression tree executed when the result is true.

Example

            int a = 10;
            int b = 10;
            
            if (a == b)
            {
                ("a == b for true,The statement is executed");
            }

            ();

Use the expression tree to implement the following

            ParameterExpression a = (typeof(int), "a");
            ParameterExpression b = (typeof(int), "b");
            MethodCallExpression call = (
                null,
                typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }),
                ("a == b for true,The expression tree is executed"));

            ConditionalExpression _if = ((a, b),call);

            Expression<Action<int, int>> lambda = <Action<int, int>>(_if,a,b);
            ()(10,10);

            ();

The generated expression tree is as follows

.Lambda #Lambda1<`2[System.Int32,System.Int32]>(
    System.Int32 $a,
    System.Int32 $b) {
    .If ($a == $b) {
        .Call ("a == b for true,The expression tree is executed")
    } .Else {
        .Default()
    }
}

if...else

if...else is represented by the following expression tree

 ConditionalExpression IfThenElse(Expression test, Expression ifTrue, Expression ifFalse);

The sample code is as follows

            int a = 10;
            int b = 11;

            if (a == b)
            {
                ("a == b for true,This statement is executed");
            }
            else
            {
                ("a == b for false,This statement is executed");
            }
            ();

Implementation using the expression tree as follows

            ParameterExpression a = (typeof(int), "a");
            ParameterExpression b = (typeof(int), "b");
            MethodCallExpression call1 = (
                null,
                typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }),
                ("a == b for true,This expression tree is executed"));

            MethodCallExpression call2 = (
                null,
                typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }),
                ("a == b for false,This expression tree is executed"));

            ConditionalExpression _if = ((a, b), call1,call2);

            Expression<Action<int, int>> lambda = <Action<int, int>>(_if, a, b);
            ()(10, 11);

            ();

The generated expression tree is as follows

.Lambda #Lambda1<`2[System.Int32,System.Int32]>(
    System.Int32 $a,
    System.Int32 $b) {
    .If ($a == $b) {
        .Call ("a == b for true,This expression tree is executed")
    } .Else {
        .Call ("a == b for false,This expression tree is executed")
    }
}

switch

The sample code is as follows

            int a = 2;
            switch (a)
            {
                case 1:("a == 1");break;
                case 2:("a == 2");break;
                default:("a != 1 && a = 2");
            }

            ();

Each case is represented by the SwitchCase type, and the SwitchCase type is generated using the SwitchCase type.

Used to build a switch expression tree,

There are many overloads, and this is commonly used

SwitchExpression Switch(Expression switchValue, Expression defaultBody, params SwitchCase[] cases);

switchValue represents the incoming parameter;

defaultBody represents the expression executed by default;

cases means multiple cases.

The above code is written using the expression tree as follows

            ParameterExpression a = (typeof(int), "a");
            MethodCallExpression _default = (
                null,
                typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }),
                ("a != 1 && a = 2"));

            SwitchCase case1 = (
                (null,
                typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }),
                ("a == 1")),
                new ConstantExpression[] { (1) }
                );

            SwitchCase case2 = (
                (null,
                typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }),
                ("a == 2")),
                new ConstantExpression[] { (2) }
                );

            SwitchExpression _switch = (a, _default, new SwitchCase[] { case1, case2 });
            Expression<Action<int>> lambda = <Action<int>>(_switch, a);
            ()(1);

            ();

The generated expression tree is as follows

.Lambda #Lambda1<`1[System.Int32]>(System.Int32 $a) {
    .Switch ($a) {
    .Case (1):
            .Call ("a == 1")
    .Case (2):
            .Call ("a == 2")
    .Default:
            .Call ("a != 1 && a = 2")
    }
}

Strangely, there is no break, but the expression tree is normal and runs without problems;

?? and ?:

?? represents a null merge operator, for examplea ?? b, if a is not null, it returns a, otherwise it returns b;

Common definitions are as follows

BinaryExpression Coalesce(Expression left, Expression right)

I won't go into details here.

?: is a ternary operator, such as a > b ? a : b .

Common definitions are as follows

ConditionalExpression Condition(Expression test, Expression ifTrue, Expression ifFalse)

You can refer to the if...else expression tree above, which will not be repeated here.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.