Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About C# Expression.MakeBinary(),how to use

Tags:

c#

expression

About Expression.MakeBinary()

BinaryExpression MakeBinary (
    ExpressionType binaryType, 
    Expression left, 
    Expression right, 
    bool liftToNull,
    MethodInfo method
);

sample:

        return Visit(expression);  
    }  

    protected override Expression VisitBinary(BinaryExpression b)  
    {  
        if (b.NodeType == ExpressionType.AndAlso)  
        {  
            Expression left = this.Visit(b.Left);  
            Expression right = this.Visit(b.Right);  

            // Make this binary expression an OrElse operation instead of an AndAlso operation.  
            return Expression.MakeBinary(ExpressionType.OrElse, left, right, b.IsLiftedToNull, b.Method);  
        }  

Microsoft documentation explanation:b.IsLiftedToNull true if the operator's return type is lifted to a nullable type; otherwise, false.

I don't understand what that means,What effect does true or false have? What does b.Method do?

like image 868
whuanle Avatar asked May 18 '26 01:05

whuanle


1 Answers

The documentation for BinaryExpression itself is helpful to answer these questions.

Note that there are three overloads for this method:

MakeBinary(ExpressionType, Expression, Expression)

MakeBinary(ExpressionType, Expression, Expression, Boolean, MethodInfo)

MakeBinary(ExpressionType, Expression, Expression, Boolean, MethodInfo, LambdaExpression)

The one you refer to is the second of the three.

Lifted Operators

A lifted operator allows an operator on a non-nullable type to be used with the nullable equivalent as well.

e.g:

int a = 1; int b = 2; int c = a + b

Here, the + operator is defined for int, int.

But:

int? a = 1; int? b = 2; int? c = a + b

Here, the + operator isn't defined in the language specification for int?, int?, and so the compiler "lifts" the operator, allowing it to work in this instance.

So for the question, a BinaryExpression "Represents an expression that has a binary operator"; and if IsLiftedToNull is true, it would be "Represents an expression that has a nullable binary operator".

Method

Instead of relying on a predefined operator, You can specify the method to use for the binary operation here.

like image 80
simonalexander2005 Avatar answered May 20 '26 15:05

simonalexander2005



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!