liveBook · Manning

Garbage collection

As explained in .NET in Action, Second Edition

A garbage collector is a runtime component that identifies unreachable allocated memory and reclaims it for future allocations.

Garbage collection is the .NET runtime’s way of reclaiming memory that an application no longer uses. CoreCLR tracks references to allocated memory; when no references remain, that memory can be made available for future allocations. This removes the need to free ordinary C# arrays explicitly. section 1.5.3 section 1.5

Listing 1.1 Creating a dynamic array in C++
#include <stdio.h>
#include <stdlib.h>
 
int main() {
   int n = 4, i, *p;
   p = (int*) malloc(n * sizeof(int));                  #1
 
   if(p == NULL) {                                      #2
      printf("\nError! memory not allocated.");
      exit(0);
   }
   printf("\nEnter elements of array : ");
 
   for(i = 0; i < n; i++) {
      scanf("%d", p + i);                               #3
   }
   printf("\nSum : %d", sum(p, n));
   free(p);                                             #4
   return 0;
}
 
int sum(int *arr, int length) {                         #5
  int i, sum = 0;
  for (i = 0; i < length; i++) {
    sum += *(arr + i);
  }
  return sum;
}

The C++ dynamic-array example checks whether allocation succeeded and calls free(p) when finished. Those responsibilities make manual memory management easy to get wrong. section 1.5.3

Listing 1.2 Creating a dynamic array in C#
public class Program
{
  public static void Main()
  {
    int n = 4, i;
    int[] p = new int[n];                                 #1
 
    Console.WriteLine("Enter elements of array : ");
 
    for (i = 0; i < n; i++) {
        p[i] = int.Parse(Console.ReadLine());             #2
    }
 
    Console.WriteLine("Sum : " + Sum(p));                 #3
  }
 
  private static int Sum(int[] arr)
  {
    int i, sum = 0;
    for (i = 0; i < arr.Length; i++)                      #4
    {
      sum += arr[i];
    }
 
    return sum;
  }
}

The corresponding C# example creates an array with new int[n] and uses it without an explicit free call. If allocation initially fails, the collector tries to reclaim memory and retry; if insufficient memory remains, .NET throws OutOfMemoryException. section 1.5.3

The distinction matters most for dynamically sized data. A function’s local variables, arguments, and return information occupy a stack frame; dynamically allocated chunks occupy the heap. An array sized from a runtime value illustrates why heap allocation is useful. 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
}

ReadNInts allocates an array using count, fills it, and returns it. Its C++ counterpart allocates a dynamic array with new; the C# version has no matching explicit release step. section 10.3.4

Automatic reclamation has a performance cost: a collection can introduce an unpredictable pause. That matters in real-time applications such as games, even though .NET is also used for game scripting and some complete engines. When investigating performance, PerfView’s GCStats reports collection counts, total pauses, and allocated memory by generation. section 1.2.1 section 10.3.4

How .NET in Action, Second Edition covers it

How deep it goes
Explains reference-based reclamation, allocation retry, stack and heap, and observable pauses without specifying a collector implementation.
Examples
Compares C++ and C# dynamic arrays and uses a PerfView GCStats table showing collection counts, pauses, and allocations.
What it assumes
Assumes familiarity with basic array code while introducing stack and heap through a C/C++ memory-management comparison.
What you can do after
Diagnose/debug with PerfView GCStats to inspect collection counts, total pauses, and allocations by generation.
How it connects
Connects garbage collection to heap allocation, stack frames, exceptions, and performance profiling.

Also explained in

Compare how 9 books explain garbage collection →

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.