views:

356

answers:

4

If I am evaluating two variables and not two method calls does it matter weather I use "&&" or "&"

//some logic that sets bool values

boolean X = true;
boolean Y = true;

if (X & Y){
   // perform some operation
}

if (X && Y){
   // perform some operation
}

Further a book I am using for C# 3.0 / .NET 3.5 only makes reference to the && operator, is the & operator going away?

+8  A: 

Always use && if you are performing a true/false logic test. A single & performs a bit-wise 'and'. It make work like a logic test in some cases but it is not guaranteed to work for all logic cases. The most common use of a single & is when applying a bit-mask.

Examples (&&):

true && true == true

Example (&):

00101001 & 00100001 = 00100001
vfilby
+1  A: 

& is a bitwise operator while && is the AND operator. Two completely different operations.

int a = 1;
int b = 2;
assert (a & b == 0) 
assert (a && b == true)

EDIT: Ooops...this example doesn't work in C#. It should in C++. Hopefully it illustrates the intent and the difference between the two operators.

jpoh
Robert Wagner
jpoh
Thats because int is not an 8-bit value. You need to cast the byte to an int to make it work.
FlySwat
Robert Wagner
+5  A: 

If you use a single & (And) the second part of the expression is evaluated. This could be bad if the second part relies on the first part being true. Usually always use && as the second part is not evaluated if the first part is false.

Logically the single & does a bitwise operation as others have said, which is still valid for boolean comparison/evaluation. Really the only time a single & (or |) should be used (or boolean evaluation) is if the second evaluation should always run (if it is a function call/modifier). This is bad practice through and probably why the book does not mention it.

Single & are useful with flag enums and bit masks.

The following will throw an exception of obj is null:

bool b = obj != null & obj.IsActive

But this will work:

bool b = obj != null && obj.IsActive

This is bad:

bool b = obj.IsActive && obj.SetActive(false);
bool b = obj.IsActive & obj.SetActive(false);

The & operator is here to stay.

Robert Wagner
+3  A: 

As has been observed, & is the bitwise AND operator. Raw binary math is seeming to be less and less common over time, with an increasing number of developers not really understanding bitwise arithmetic. Which can be a pain at times.

However there are a lot of tasks that are best solved with such, in particular anything that looks at data as flags. The & operator is 100% necessary, and isn't going anywhere - it simply isn't used as frequently as the boolean short-circuiting && operator.

For example:

[Flags]
enum SomeEnum { // formatted for space...
    None = 0, Foo = 1, Bar = 2 // 4, 8, 16, 32, ...
}
static void Main() {
    SomeEnum value = GetFlags();
    bool hasFoo = (value & SomeEnum.Foo) != 0;
}
static SomeEnum GetFlags() { ... }
Marc Gravell