liveBook · Manning

Unsafe keyword

As explained in .NET in Action, Second Edition

The C# unsafe keyword enables code that can use pointers and perform operations the runtime cannot verify as memory-safe.

The C# `unsafe` keyword marks code the .NET runtime cannot verify as memory-safe. Inside an `unsafe` block, code can use pointers, allocate and free memory, and call methods through function pointers. The keyword does not mean the code is inherently dangerous; it means the runtime cannot verify protections such as array bounds and permitted memory access. section 10.3.4

A C# array reference is not a C++ pointer to a physical address: the garbage collector can move the array. To copy arrays through pointers, use `fixed` to keep both arrays at their physical locations until the pointer operations finish. 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 array-copy listing places pointer operations inside `unsafe` and pins both arrays with `fixed` before copying elements. section 10.3.4

How .NET in Action, Second Edition covers it

How deep it goes
Explains verification limits and works through an array-copy pattern using `unsafe` and `fixed`.
Examples
Illustrates copying an integer array through pointers, alongside C++ and C# dynamic-array examples.
What it assumes
Assumes familiarity with C# arrays and loops while explaining why array references differ from pointers.
What you can do after
Practice/perform pointer-based array copying with C# `unsafe` and `fixed` blocks.
How it connects
Connects pointers, array references, `fixed`, 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.