C# / CHAPTER 05
Arrays, value copies, and shared references
IntermediateDetermine exactly which assignments create an independent value.
By the end of this chapter
- Trace array aliases
- Distinguish struct copies from class references
- Recognize shallow copying of nested data
The idea
C# distinguishes value types from reference types. Assigning an int copies its value; assigning an array variable copies a reference to the same array. A struct is a value type, but a struct containing a reference-type field still copies that reference. This makes the ownership of nested data more important than the label on the outer type.
An array clone creates a new array container. It does not recursively clone reference-type elements. Before claiming that a function preserves its input, identify every mutable object it may reach and decide which ones must be copied. For a rectangular array, GetLength(dimension) describes each dimension, while Length counts all elements. Keep loop bounds tied to the appropriate dimension rather than assuming a square grid.
using System;
int[] a = {2, 4};
int[] alias = a;
int[] copy = (int[])a.Clone();
alias[0] = 8;
copy[1] = 9;
Console.WriteLine($"{a[0]} {a[1]} {copy[0]} {copy[1]}");8 4 2 9
The alias shares a, while the clone contains independent integer elements.
Try it yourself
Copy a two-dimensional integer array and change one cell without altering the source.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING