What is the difference between & and && operators in C#

前端 未结 9 923
误落风尘
误落风尘 2020-12-02 17:03

I am trying to understand the difference between & and &&operators in C#. I searched on the internet without success. Can somebody plea

9条回答
  •  天涯浪人
    2020-12-02 17:33

    & can be used on either integral types (like int, long etc.) or on bool.

    When used on an integral type, it performs a bitwise AND and gives you the result of that. When used on a bool, it performs a logical AND on BOTH its operands and gives you the result.

    && is not used as a bitwise AND. It is used as a logical AND, but it does not necessarily check both its operands. If the left operand evaluates to false, then it doesn't check the right operand.

    Example where this matters:

    void Action() 
    {
        string name = null;
        if(name != null && name.EndsWith("ack"))
        {
            SomeOtherAction();
        }
    }
    

    If name is null, then name.EndsWith("ack") will never get executed. It is smart enough to know if the left operand is false, then the right operand doesn't need to be evaluated (aka "short-circuiting"). That's good because calling a method on null will throw a NullReferenceException.

    If you changed it into if(name != null & name.EndsWith("ack")), both sides would get evaluated and it would throw a NullReferenceException.

    One detail: & can also be a unary operator (so it has one operand) in an unsafe context. It will give the address of a value or object. It's not important though, as most people don't ever have to touch this part of the language.

提交回复
热议问题