Do short-circuiting operators || and && exist for nullable booleans? The RuntimeBinder sometimes thinks so

后端 未结 3 983
一整个雨季
一整个雨季 2021-01-30 01:31

I read the C# Language Specification on the Conditional logical operators || and &&, also known as the short-circuiting logical operat

3条回答
  •  日久生厌
    2021-01-30 02:11

    First of all, thanks for pointing out that the spec isn't clear on the non-dynamic nullable-bool case. I will fix that in a future version. The compiler's behavior is the intended behavior; && and || are not supposed to work on nullable bools.

    The dynamic binder does not seem to implement this restriction, though. Instead, it binds the component operations separately: the &/| and the ?:. Thus it's able to muddle through if the first operand happens to be true or false (which are boolean values and thus allowed as the first operand of ?:), but if you give null as the first operand (e.g. if you try B && A in the example above), you do get a runtime binding exception.

    If you think about it, you can see why we implemented dynamic && and || this way instead of as one big dynamic operation: dynamic operations are bound at runtime after their operands are evaluated, so that the binding can be based on the runtime types of the results of those evaluations. But such eager evaluation defeats the purpose of short-circuiting operators! So instead, the generated code for dynamic && and || breaks the evaluation up into pieces and will proceed as follows:

    • Evaluate the left operand (let's call the result x)
    • Try to turn it into a bool via implicit conversion, or the true or false operators (fail if unable)
    • Use x as the condition in a ?: operation
    • In the true branch, use x as a result
    • In the false branch, now evaluate the second operand (let's call the result y)
    • Try to bind the & or | operator based on the runtime type of x and y (fail if unable)
    • Apply the selected operator

    This is the behavior that lets through certain "illegal" combinations of operands: the ?: operator successfully treats the first operand as a non-nullable boolean, the & or | operator successfully treats it as a nullable boolean, and the two never coordinate to check that they agree.

    So it's not that dynamic && and || work on nullables. It's just that they happen to be implemented in a way that is a little bit too lenient, compared with the static case. This should probably be considered a bug, but we will never fix it, since that would be a breaking change. Also it would hardly help anyone to tighten the behavior.

    Hopefully this explains what happens and why! This is an intriguing area, and I often find myself baffled by the consequences of the decisions we made when we implemented dynamic. This question was delicious - thanks for bringing it up!

    Mads

提交回复
热议问题