liveBook · Manning

Array

As explained in .NET in Action, Second Edition

An array is an indexed, typically fixed-size sequence of elements of a specified type.

A C# array holds a fixed number of indexed elements. Create one with `new int[count]`, fill positions from `0` to `count - 1`, and return the array. Code uses an array reference rather than a pointer to its memory location. section 10.3.4

Listing 10.9 C# code to read numbers into a dynamic array
int[] ReadNInts(int count)
{
  int[] arr = new int[count];       #1
  for (int i = 0; i < count; i++)
  {
    arr[i] = readInt();             #2
  }
  return arr;                       #3
}

The `ReadNInts` listing allocates an array, fills it by index, and returns it. section 10.3.4

That reference matters when memory is tight. Garbage collection can remove unused allocations yet leave free space in separate gaps. Compaction moves remaining allocations together to make room; code using an array reference can continue to refer to the array after it moves. Compaction can also pause that code, so allocation behavior matters in latency-sensitive applications. section 10.3.4

Listing 10.10 C# copy array using pointers instead of references
int[] CopyArray(int[] source)
{
  int length = source.Length;
  int[] target = new int[length];           #1
  unsafe                                    #2
  {
    fixed (int* pSource = source,           #3
           int* pTarget = target)
    {
      for (int i = 0; i < length; i++)
      {
        pTarget[i] = pSource[i];            #4
      }
    }
  }
  return target;                            #5
}

The pointer-based copy uses `unsafe` and `fixed` to access array elements through pointers—a contrast with ordinary array-reference code. section 10.3.4

How .NET in Action, Second Edition covers it

How deep it goes
Shows allocation, indexed access, and a pointer-based copy, then explains compaction without detailing garbage-collector algorithms.
Examples
Uses C# array-reading and pointer-copy listings alongside heap-allocation diagrams.
What it assumes
Assumes familiarity with C# syntax; illustrates heap allocation and compaction through diagrams.
What you can do after
Evaluate/understand how array references allow compaction and why collection pauses matter for latency.
How it connects
Connects arrays to references, pointers, heap allocation, garbage collection, and compaction.

Also explained in

Compare how 40 books explain array →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.