C# Foundations · Lesson 28

Array aliases and independent copies

Choose whether a second variable shares or copies an array.

How it works

An array is a reference type. Assigning one array variable to another copies the reference, so the two variables identify the same array object. An array-copy operation creates a separate array container. These are different operations even though both can produce a second variable containing the same initial sequence of values.

A copy is useful when a calculation needs a stable input snapshot or an experiment should not modify the original data. The depth of that copy matters. Copying an array of integers duplicates the integer values. Copying an array of mutable objects duplicates references to those objects, not every reachable object. Describe the boundary you need instead of assuming that the word copy always means complete independence.

Walk through the example. The alias points to the source array, while ToArray creates another integer array with the same values. Updating the first element through the alias therefore changes source. Updating the second element of the copied array changes only the copy. The final ReferenceEquals calls check container identity directly and make the sharing relationship visible.

Watch the boundary. A property that exposes an array gives callers a way to mutate its elements, even if the property itself has no setter. Conversely, returning a fresh array every time may add unnecessary work for large data. Choose between ownership transfer, a snapshot, and read-only access based on the caller's needs. Do not use a copy merely to hide an unclear mutation contract.

Practice independently. Model a daily score snapshot. Create an original array, an alias, and a copied array, then change one element through each variable and write down the expected contents before running. Repeat with an array containing a mutable class and explain the difference. Finally write a function that returns a sorted copy while leaving the supplied array's order unchanged.

A working example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;

int[] source = { 1, 2, 3 };
int[] alias = source;
int[] copy = source.ToArray();
alias[0] = 9;
copy[1] = 8;
Console.WriteLine(string.Join(",", source));
Console.WriteLine(string.Join(",", copy));
Console.WriteLine(ReferenceEquals(source, alias));
Console.WriteLine(ReferenceEquals(source, copy));

Expected output

9,2,3
1,8,3
True
False
Try this
A new array container does not automatically clone objects stored inside it.