89

I came across this:

bool Isvalid = isValid & CheckSomething()

bool Isvalid = isValid && CheckSomething()

The second case could be a scenario for short circuiting.

So can't we always use just & instead of &&?

Servy
  • 202,030
  • 26
  • 332
  • 449
V4Vendetta
  • 37,194
  • 9
  • 78
  • 82
  • 4
    Don't use & unless you're dealing with bits. If you're not sure, always use &&. – Ilya Kogan Apr 04 '11 at 11:14
  • 1
    @Ilya: And what if you're not dealing with bits but the second operand has to be evaluated for some reason? – LukeH Apr 04 '11 at 11:24
  • 6
    @LukeH Then your code is unreadable. Better call what you need to call explicitly and not inside a boolean logic expression. How many of the programmers who are going to maintain your system know about this hidden feature of C#? – Ilya Kogan Apr 04 '11 at 11:37
  • 4
    @Ilya: I certainly wouldn't advocate the use of `&` (or of side-effecting expressions in general); I'm simply showing the difference between the two operators! (By the way, the difference between `&` and `&&` isn't really a hidden feature of C#, it's common to all the C-like languages that I'm aware of. If the people maintaining your system don't know the difference then they need some training asap.) – LukeH Apr 04 '11 at 11:53
  • Yes, the difference is short-circuit evaluation. But you have it backwards: you should almost always use `&&`. It's difficult to give any better an answer than that. The two operators are features of the language for a reason. No one can just tell you to ignore one of them. – Cody Gray - on strike Apr 04 '11 at 12:54
  • `&` and `&&` do **not** necessarily have the same outputs for boolean inputs because of a discrepancy in C# and CLI specifications: http://stackoverflow.com/q/24683107/3303123 – mallardz Jul 11 '14 at 09:55

4 Answers4

100

& is a bitwise AND, meaning that it works at the bit level. && is a logical AND, meaning that it works at the boolean (true/false) level. Logical AND uses short-circuiting (if the first part is false, there's no use checking the second part) to prevent running excess code, whereas bitwise AND needs to operate on every bit to determine the result.

You should use logical AND (&&) because that's what you want, whereas & could potentially do the wrong thing. However, you would need to run the second method separately if you wanted to evaluate its side effects:

var check = CheckSomething();
bool IsValid = isValid && check;
MarredCheese
  • 17,541
  • 8
  • 92
  • 91
Talljoe
  • 14,593
  • 4
  • 43
  • 39
  • 27
    Both forms are logical ANDs when applied to booleans; it's just that the `&&` version is short-circuiting. – LukeH Apr 04 '11 at 11:13
  • 1
    @LukeH: So it won't make any difference if i use **&** or **&&** (other than short circuiting part)? – V4Vendetta Apr 04 '11 at 11:24
  • 6
    @V4Vendetta: If you use `&` then `CheckSomething` will always be called, regardless of the value of `isValid`. If you use `&&` then `CheckSomething` will only be called when `isValid` is true. The result of the expression itself should be the same regardless of whether you use `&` or `&&`. (It's up to you to decide in what circumstances you need `CheckSomething` to be called.) – LukeH Apr 04 '11 at 11:28
  • 3
    @LukeH, People who use `&` for boolean expressions are those programmers who like to play around with language features without thinking how unreadable their code is going to be. – Ilya Kogan Apr 04 '11 at 11:40
  • 1
    @Ilya: Agreed. I'm certainly not advocating the use of `&` (or of side-effecting expressions in general); I'm simply explaining the difference between the two operators! – LukeH Apr 04 '11 at 11:52
  • 3
    @LukeH Apparently `&` and `&&` do ***not*** always have the same outputs when used with boolean values due to a discrepancy between C# and CLI specifications. See my question here: http://stackoverflow.com/q/24683107/3303123 – mallardz Jul 11 '14 at 09:51
  • 2
    Just for the record, what you call as bit-wise operators is called logical operators and what you call as logical operators is called conditional operators. Maybe it would be better to stick to naming declared by MS in ordeer to avoid confusion if not properly declared by yourself. Source: http://msdn.microsoft.com/cs-cz/library/6a71f45d.aspx. – Ondrej Janacek Aug 26 '14 at 13:30
  • 4
    [This answer is being discussed on meta.](https://meta.stackoverflow.com/questions/366943/edited-incorrect-answer-edit-was-rolled-back) – Script47 Apr 30 '18 at 22:35
  • 1
    "*[To be very exact, in C#, those operators (&, | [and ^\]) are called "Logical operators" (see the C# spec, chapter 7.11).](https://stackoverflow.com/questions/7331686/why-and-not/7331721#7331721)*" – Peter Mortensen May 01 '18 at 22:24
  • 2
    Even though & actually might be a bitwise operator when having booleans as operands, this documentation does not talk about it that way: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators#logical-and-operator- – Mattias Nordqvist Sep 13 '19 at 21:02
  • 2
    The & and | are Boolean comparisons when applied to boolean expression...they perform bitwise comparison when applied to numbers. (C and C++ dont act like this.) – Chris Catignani Nov 15 '20 at 18:45
  • 2
    This answer is not correct in application to C#. Other languages use `&` as bitwise, but C# uses it as a bitwise only when used on integral values, but with Boolean values it will not act as bitwise, but a logical AND which evaluates both operands. See [this link](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators#:~:text=null%2Dforgiving%20operator.-,Logical%20AND%20operator%20%26,Otherwise%2C%20the%20result%20is%20false%20.). The answer by `adjan` should be marked as the correct answer. – Hawkeye Aug 11 '21 at 21:45
55

C# has two types of logical conjunction (AND) operators for bool:

  1. x & y Logical AND

    • Results in true only if x and y evaluate to true
    • Evaluates both x and y.
  2. x && y Conditional Logical AND

    • Results in true only if x and y evaluate to true
    • Evaluates x first, and if x evaluates to false, it returns false immediately without evaluating y (short-circuiting)

So if you rely on both x and y being evaluated you can use the & operator, although it is rarely used and harder to read because the side-effect is not always clear to the reader.

Note: The binary & operator also exists for integer types (int, long, etc.) where it performs bitwise logical AND.

adjan
  • 13,371
  • 2
  • 31
  • 48
  • 1
    Can you give an example of when & would have a practical use in C#? – eaglei22 Jul 10 '18 at 14:55
  • @eaglei22 `var bob = true; var bob2 = true; var bob3 = bob & bob2;` On many CPUs, `&` in that example would be faster than `&&`. – mjwills Oct 30 '18 at 23:21
  • Thanks for a "logical" explanation. – Chris Catignani Nov 15 '20 at 18:57
  • 1
    This really needs to be marked as the correct answer. The answer by Talljoe is misinformed about C# characteristics and would lead a reader who does not read all the comments and answers to the wrong conclusion. – Hawkeye Aug 11 '21 at 21:36
  • @Chris Catignani if you have a method that makes an evaluation and you still want it to run. For example if(evalA() & evalB()) you may want B to run (maybe to set a private bool variable) even if A is false. Personally, I would split it if that is needed. – A_Arnold Jul 26 '23 at 18:49
15

In && the second expression is only evaluated if the first one is true.

And & is just a way to concatenate the two expressions, like true & true = true, true & false = false etc.

opiswahn
  • 435
  • 1
  • 5
  • 17
7

I believe you are missing something. In the second scenario CheckSomething is not evaluated if isValid is false

The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.

http://msdn.microsoft.com/en-us/library/2a723cdk(v=vs.71).aspx

Pleun
  • 8,856
  • 2
  • 30
  • 50