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

前端 未结 9 919
误落风尘
误落风尘 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:51

    & is the bitwise AND operator. For operands of integer types, it'll calculate the bitwise-AND of the operands and the result will be an integer type. For boolean operands, it'll compute the logical-and of operands. && is the logical AND operator and doesn't work on integer types. For boolean types, where both of them can be applied, the difference is in the "short-circuiting" property of &&. If the first operand of && evaluates to false, the second is not evaluated at all. This is not the case for &:

     bool f() {
        Console.WriteLine("f called");
        return false;
     }
     bool g() {
        Console.WriteLine("g called");
        return false;
     }
     static void Main() {
        bool result = f() && g(); // prints "f called"
        Console.WriteLine("------");
        result = f() & g(); // prints "f called" and "g called"
     }
    

    || is similar to && in this property; it'll only evaluate the second operand if the first evaluates to false.

    Of course, user defined types can overload these operators making them do anything they want.

提交回复
热议问题