3

I have come across a piece of code that I can't wrap my head around:

public void Connect()
{
    if (!(!string.IsNullOrEmpty(_vpnConnectionName) & !string.IsNullOrEmpty(_ipToPing)))
    {
        return;
    }

    GetConnected();
}

I've researched the single ampersand on SO and elsewhere, and found it is a Bitwise AND operand. However the explanations all revolve around integers.

I can understand the applicability of bitwise operations on integers, but how are they applicable to booleans?

Community
  • 1
  • 1
Chris Schiffhauer
  • 17,102
  • 15
  • 79
  • 88
  • 1
    Try to avoid asking two questions in the same question. Typically only one gets answered – Eric Lippert Apr 10 '14 at 14:13
  • 4
    Look up demorgans law and you'll find that your transformation is correct. – Eric Lippert Apr 10 '14 at 14:20
  • 1
    There is no distinction between *int* and *bool* after the C# compiler is done with it. The CLR treats them as ints with the expected outcome when you logically-and them. Also the reason that VB.NET's True is -1, a language that historically did not distinguish between logical and bit-wise AND. So the answer to Eric's comment "are bools bits" is Yes. – Hans Passant Apr 12 '14 at 22:41

2 Answers2

8

It is a logical operator on bools that evaluates both sides regardless of the value of the left side.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
  • @Eric I believe it is a bitwise operator, certainly on the IL level. This comes to play with booleans that are not 0 or 1 which are legal on the CLR. Is that true? See http://pastebin.com/U7vqpn6G This would be reproducible using verifiable, safe IL. – usr Apr 10 '14 at 14:14
  • @usr people who store things other than zero or one in a boolean are looking for trouble and should not be surprised when they find it. – Eric Lippert Apr 10 '14 at 14:19
3

For bool, & isn't a bitwise AND operator - it's the non-short-circuiting logical AND operator - it always evaluates both arguments - as opposed to the "usual" && operator that only evaluates its second argument if its first argument is true.

(Realised that it may not be obvious, that the first & above is linked to the actual documentation)

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
  • 3
    @PaulyGlott - no, `&&` doesn't evaluate its second argument if the first argument is `false`. – Damien_The_Unbeliever Apr 10 '14 at 14:11
  • Also though `&` *behaves* like a **logical** `AND` for booleans, it certainly remains to *be* a **bitwise** `AND` operator. The bools simply are defined as such, that the bitwise operation on their bits behaves like a logical one. – MrPaulch Apr 10 '14 at 14:31