Alex Rivera | Logout

What is the second meaning of a single ampersand in C#?

Asked 2009-10-08T13:11:54.833
12

I have used the single ampersand (&) in C# to mean "check the second conditional statement even if the first is false".

But the following seems to be a different meaning of & altogether, can anyone explain how i & 1 works in the following example?

List<int> scores = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8 };
var evenScores = scores.Where(i => i % 2 == 0);
var evenScores2 = scores.Where(i => (i & 1) == 0);
Edit
Report

1 Answer

6

For boolean types, what you mentioned is how it behaves.

For integer types, it's the bitwise "and" operator.

It can be overloaded for other types.

Basically, the expression (i & 1) == 0 checks to see whether the least significant bit of i is set, which only happens if the number is odd.

answered 2009-10-08T13:14:31.913

Your Answer