Shortcut &= acting like & not &&

public static void Main()
{
    var result = false;
    Xpto xpto = null;
    result &= xpto.Some;
}

public class Xpto
{
    public bool Some { get; set; }
}

I'm using C# 6.0 VS2015; the code above triggers a null exception.

The &= operator is behaving like the & operator. I would expect it to behave similar to && and skip evaluation of the right side if value already false (see explanation of "short-circuit" behavior in The conditional-AND operator (&&) article).

Is this behavior intended or is it a bug?


Take a look at the documentation: &= Operator:

x &= y is equivalent to x = x & y

(...) The & operator performs a bitwise logical AND operation on integral operands and logical AND on bool operands.

I'm assuming you're trying to avoid the null check.

The code below will not throw an exception because you stated the result variable is false ; in this case, the language optimization will short-circuit the expression and will not evaluate the second part:

result = result && xpto.Some;

If you're a on liner person, you can make it more same by writing:

result = result && (xpto == null ? true : xpto.Some);

or, in plain C#:

if (xpto != null)
   result = result && xpto.Some;
链接地址: http://www.djcxy.com/p/13062.html

上一篇: C#6.0空传播操作员和属性分配

下一篇: Shortcut&= like like&not &&