Why does C# && and || operators work the way they do?

前端 未结 7 1958
余生分开走
余生分开走 2020-12-06 14:25

here is a tl;dr

I come from a C++ background. && is suppose to check if left side is true and right side is true. what does & have anything to do with th

相关标签:
7条回答
  • 2020-12-06 14:56

    C# is more type safe then C++.

    Firstly & is overloaded, there are two versions one is the bitwise AND which operates on two integral types (such as int, long) and returns the result of AND each bit from the first argument with the corresponging bit in the second argument. For example 0011 & 1010 == 0010.

    The second overload is logical AND which operates on two boolean types (bool), it returns true if and only if both arguments are also true.

    Finally you have && which is conditional AND, again it operates two boolean types and returnes true if and only if both arguments are true but it also has the added guarentee that if the first arugment is true the second argument will not be evaluated. This allows you to write things like if(arr != null && arr.Length > 0)... without the short-circuiting behaviour this would give you a null reference exception.

    Rules for | and || are similar, | is overloaded for bitwise and logical OR, and || is the conditional OR.

    The reason your possible getting confused with C++ behaviour is that integral types are implicitly convertable to bools in C++, 0 is false and anything else is true, so 5 && 5 returns true in C++. In C# intergral types are not implicitly convertable to bools so 5 && 5 is a type error. && and || are also short-circuiting in C++ however, so you shouldn't be suprised at that being the same in C#.

    0 讨论(0)
提交回复
热议问题