liveBook · Manning

Fixed keyword

As explained in .NET in Action, Second Edition

The C# fixed keyword prevents referenced managed objects from being relocated by garbage collection within a fixed statement or block.

A C# pointer refers to a memory location. If garbage collection moves an array during heap compaction, a pointer to its former location is no longer suitable for accessing it. A fixed block keeps the array at the same physical memory location until the block ends. section 10.3.4

For pointer-based array copying, declare pointers to both the source and target arrays in fixed, then copy their elements inside the block. The surrounding unsafe block permits pointer use; fixed addresses the separate problem of keeping those arrays from moving. 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 copy loop reads through pSource and writes through pTarget while both arrays are fixed. section 10.3.4

How .NET in Action, Second Edition covers it

How deep it goes
Explains fixed through a working array-copy listing and garbage-collection compaction, without detailing pinning internals.
Examples
Uses a C# loop that copies an array through fixed source and target pointers.
What it assumes
Assumes C# array and loop familiarity while explaining why pointers require protection from relocation.
What you can do after
Apply it via C# fixed blocks to keep arrays stationary during pointer-based copying.
How it connects
Connects fixed to unsafe code, pointers, garbage collection, and heap compaction.

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.