skip to content

In C#, what does var ready = proofed.And(paid); do to the BitArray named proofed, and when does that call throw?

level: middleimportance: nice to knowfreq 12%

answer

  1. returns this, not a copy
  2. the receiver is overwritten
  3. copy constructor first
  4. lengths must match

basics

~10 s

BitArray.And writes the result into proofed and returns proofed itself, so ready and proofed are the same object and the original flags are lost. It throws ArgumentException when the two lengths differ.

solid answer

~30 s

`And`, `Or`, `Xor` and `Not` on `System.Collections.BitArray` modify the instance you call them on and return that same instance for chaining. So `var ready = proofed.And(paid);` overwrites `proofed` with the AND, `ready` is just another reference to it, and `paid` is untouched. If you still need the original flags, copy first: `var ready = new BitArray(proofed).And(paid);`. The operands must have the same `Length`, or the call throws `ArgumentException` ("Array lengths must be the same.") before changing anything; a `null` operand throws `ArgumentNullException`. `BitArray` also predates generics: it is not `IEnumerable<bool>`, so `foreach (var b in bits)` yields boxed `object` values.

code

csharp · 23 lines
csharp
using System.Collections;

var proofed = new BitArray(8);
var paid = new BitArray(8);
proofed[1] = proofed[3] = true;
paid[3] = paid[5] = true;

BitArray ready = proofed.And(paid);           // writes into proofed
Console.WriteLine(ReferenceEquals(ready, proofed));
Console.WriteLine(Bits(proofed));             // job 1's proofed flag is gone

var safe = new BitArray(paid).And(new BitArray(8) { [5] = true });
Console.WriteLine(Bits(safe) + " " + Bits(paid));

try { proofed.Or(new BitArray(16)); }
catch (ArgumentException ex) { Console.WriteLine($"{ex.GetType().Name}: {ex.Message}"); }

static string Bits(BitArray bits)
{
    var chars = new char[bits.Length];
    for (int i = 0; i < bits.Length; i++) chars[i] = bits[i] ? '1' : '0';
    return new string(chars);
}

go deeper

for a junior

Remember that BitArray's And, Or, Xor and Not change the BitArray you call them on and return that same object.

for a middle

Explain the in-place contract, copy with new BitArray(other) before a destructive call, and know the ArgumentException for mismatched lengths.

for a senior

Flag assignments like var result = a.And(b) in review as hidden mutations, and know when a ulong, a [Flags] enum or a HashSet<int> beats BitArray.

for a principal

Use BitArray as an example when setting review guidance that APIs returning their receiver must be read as mutating, not as producing copies.

## A mutating API that reads like a pure one `System.Collections.BitArray` is a compact set of boolean flags: each flag takes one bit, packed into an internal array, instead of the byte per element a `bool[]` uses. It has an indexer (`bits[i]`), `Get` and `Set`, `SetAll`, and four bitwise operations: `And`, `Or`, `Xor` and `Not`. Those four look like functions that return a new value: ```csharp BitArray ready = proofed.And(paid); ``` They are not. The methods' own documentation says the current `BitArray` "will be modified to store the result", and that the return value is "a reference to the current BitArray object". So after that line: - `proofed` now holds the AND of the two arrays; its original flags are gone. - `ready` and `proofed` are the **same object** (`ReferenceEquals(ready, proofed)` is `true`). - `paid` is unchanged. - Any later change through `ready` also changes `proofed`. The return value exists for chaining (`a.And(b).Or(c)`), not to signal a copy. `LeftShift(int)` and `RightShift(int)` follow the same pattern: they shift in place and return the current instance. In a print shop that tracks, for 500 job slots, which jobs are proofed and which are paid, code that computes "ready to print" this way silently loses the proofed state for every job that is not yet paid, and the next report built from `proofed` is wrong without any exception. ## Copy first when you need the operand later The fix is to operate on a copy: 1. `new BitArray(proofed)` copies the bits (the copy constructor), as does `(BitArray)proofed.Clone()`. 2. Call `And`, `Or`, `Xor` or `Not` on the copy: `var ready = new BitArray(proofed).And(paid);` 3. Keep using `proofed` and `paid` as before. If the in-place update *is* what you want, write it as a statement (`proofed.And(paid);`) rather than assigning the result to a new name, so readers are not misled into thinking a new array was created. ## Length rules | Situation | Result | |---|---| | `And`, `Or` or `Xor` with arrays of different `Length` | `ArgumentException` ("Array lengths must be the same.") | | either operand `null` | `ArgumentNullException` | | `new BitArray(-1)` or `Length = -1` | `ArgumentOutOfRangeException` | | `bits[i]` with `i` outside `0` to `Length - 1` | `ArgumentOutOfRangeException` | | setting `Length` larger | new bits are `false` | | setting `Length` smaller | trailing bits are discarded | The length check happens before any bits are touched, so a mismatched `And` leaves the target unchanged. ## Getting bits in and out Besides `BitArray(int length)` and `BitArray(int length, bool defaultValue)`, there are constructors that take a `bool[]`, a `byte[]`, an `int[]` or another `BitArray`, so flags loaded from a file or a database column can be wrapped directly. In the other direction, `CopyTo(Array, int)` accepts an `int[]`, a `byte[]` or a `bool[]` and throws `ArgumentException` for any other array type. Copying to an `int[]` or `byte[]` is the compact way to persist the flags, since it writes the packed bits rather than one value per flag. ## What BitArray is not - **Not generic.** It lives in the old non-generic `System.Collections` namespace and implements `ICollection`, not `IEnumerable<bool>`. Its enumerator yields `object`, so `foreach (var b in bits)` gives you boxed values typed as `object`: `bool x = b;` fails with **CS0266**. Write `foreach (bool b in bits)` so the compiler inserts the cast, or use a `for` loop over the indexer, which avoids the boxing. - **Not a set of integers.** It is a fixed-length flag array addressed by index; for an arbitrary set of ids, `HashSet<int>` fits better. - **Not thread-safe.** Concurrent writers can produce wrong bits. - **Not always the smallest option.** For 64 flags or fewer, a single `ulong` or a `[Flags]` enum is smaller still and needs no object at all. ## Why interviewers ask The question is less about bit packing than about reading an API's contract. `BitArray` predates generics, and its "modify and return this" style is easy to misread: LINQ operators, `string` methods and immutable collections all return new results, so a returned value looks like a copy. `StringBuilder.Append` is the familiar API that works the same way as `BitArray`. A candidate who checks whether a method mutates its receiver, and copies before a destructive call, will avoid the same trap in other APIs too.

  • Why does foreach (var b in bits) followed by bool x = b; not compile for a BitArray?
    `BitArray` implements only the non-generic `ICollection`, so its enumerator's `Current` is `object` and `var` infers `object`. Assigning that to `bool` needs an explicit cast, so the compiler reports CS0266. Writing `foreach (bool b in bits)` makes the compiler insert the cast; a `for` loop over the indexer avoids boxing entirely.
  • When is a BitArray the wrong choice for a set of flags?
    With 64 flags or fewer, a `ulong` or a `[Flags]` enum is smaller and allocation-free. When the members are arbitrary ids rather than dense positions from 0 to n - 1, a `HashSet<int>` fits better. `BitArray` earns its place for a large, dense, fixed range of flags, such as one per job slot.

  • BitArray.And returns a new BitArray and leaves both operands unchanged.
  • And on BitArrays of different lengths pads the shorter one with false.
  • A BitArray stores each flag in a full byte, like a bool array.
  • BitArray implements IEnumerable<bool>, so foreach with var yields bool.
  • Only Not modifies the BitArray; And, Or and Xor return copies.