C# Composite Types

A composite type groups several values into one unit with a name. C# has four ways to declare your own: struct and class, and their data-focused shortcuts record struct and record. The standard library adds ready-made containers — arrays, List<T>, Dictionary<TKey, TValue> — and tuples for quick, unnamed groups. The one idea that ties them together is the difference between value and reference semantics, introduced in Data Types.

All examples are complete dotnet new console programs (.NET 8 or later). Type declarations go after the top-level statements in the same file.

Value vs Reference Semantics

Copying vs Sharing

A struct is a value type: the variable contains the data. Assigning it to another variable, or passing it to a method, copies all its fields. A class is a reference type: the variable contains a reference to an object that lives on the heap, so assignment copies the reference and both variables then point to the same object. The program below makes the difference visible.

// Assigning or passing a struct copies it; a class instance is shared.
var a = new PointStruct(1, 2);
var b = a;            // b is an independent copy
b.X = 99;
Console.WriteLine($"struct: a.X={a.X}, b.X={b.X}");

var p = new PointClass(1, 2);
var q = p;            // q refers to the same object as p
q.X = 99;
Console.WriteLine($"class:  p.X={p.X}, q.X={q.X}");

MoveStruct(a);        // the method receives a copy
MoveClass(p);         // the method receives the reference
Console.WriteLine($"after Move: a.X={a.X}, p.X={p.X}");

static void MoveStruct(PointStruct s) => s.X += 10;
static void MoveClass(PointClass c) => c.X += 10;

struct PointStruct(int x, int y)
{
    public int X = x;
    public int Y = y;
}

class PointClass(int x, int y)
{
    public int X = x;
    public int Y = y;
}

Output:

struct: a.X=1, b.X=99
class:  p.X=99, q.X=99
after Move: a.X=1, p.X=109

The (int x, int y) after the type name is a primary constructor (C# 12): its parameters are in scope for the whole body and here initialise the fields. To let a method change the caller's struct, pass it with ref — see Functions & References.

Structs

Use a struct for a small value that is defined entirely by its data and is usually treated as a single number-like thing: a point, a colour, a date, a money amount. The built-in int, double, DateTime and TimeSpan are all structs. Microsoft's design guidelines give a good rule of thumb: a struct should be small (roughly 16 bytes or less), immutable, and rarely boxed.

Immutable Structs

Mark a struct readonly to make every field read-only. Because copies are made silently all the time, a mutable struct is a classic source of bugs: you change a copy and wonder why the original did not change. An immutable struct cannot have that problem, and "changing" it means creating a new value.

readonly struct Money
{
    public decimal Amount { get; }
    public string Currency { get; }

    public Money(decimal amount, string currency)
    {
        Amount = amount;
        Currency = currency;
    }

    public Money Add(Money other) => new(Amount + other.Amount, Currency);
    public override string ToString() => $"{Amount} {Currency}";
}

Every struct also has a parameterless state, default(Money), in which all fields are zero or null. Design your struct so that this zero state is valid, or at least harmless.

Classes

A class is the default choice for anything with identity or behaviour: a customer, a bank account, a connection, a game character. Two accounts with the same balance are still two different accounts. Classes support inheritance, can be null, and are passed around cheaply because only the reference is copied.

Fields, Properties and Methods

A class protects its data by keeping fields private and exposing properties — members that look like fields but run code. { get; } makes a property read-only after construction, and { get; private set; } lets only the class itself change it. Methods then enforce the rules, so the object can never reach an invalid state.

// A class guards its own state: callers can read Balance but only change it through methods.
var account = new BankAccount("Ada");
account.Deposit(100);
account.Withdraw(30);
Console.WriteLine(account);

try
{
    account.Withdraw(500);
}
catch (InvalidOperationException ex)
{
    Console.WriteLine(ex.Message);
}

class BankAccount
{
    public string Owner { get; }
    public decimal Balance { get; private set; }

    public BankAccount(string owner) => Owner = owner;

    public void Deposit(decimal amount)
    {
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(amount);
        Balance += amount;
    }

    public void Withdraw(decimal amount)
    {
        if (amount > Balance)
            throw new InvalidOperationException($"Insufficient funds: balance is {Balance}");
        Balance -= amount;
    }

    public override string ToString() => $"{Owner}: {Balance}";
}

Output:

Ada: 70
Insufficient funds: balance is 70

Money uses decimal, not double, because decimal stores base-10 fractions exactly. Throwing exceptions on invalid operations is covered in Error Handling.

Records

Many types exist only to carry data: a DTO from a web API, a row from a query, a configuration entry. For those, a record generates the boilerplate in one line. A positional record record Point(int X, int Y); gets a constructor, init-only properties, value-based Equals and ==, GetHashCode, a readable ToString, and a Deconstruct method.

Value Equality and with

A record (also written record class) is still a reference type, but two records with equal data compare as equal. The with expression creates a modified copy — called non-destructive mutation — which is how you "change" immutable data. A record struct gives the same conveniences for a value type; unlike a positional record class, its properties are writable unless you declare it readonly record struct.

// Records compare by value, print their data, deconstruct, and copy with "with".
var a = new Point(1, 2);
var b = new Point(1, 2);
var moved = a with { X = 5 };

Console.WriteLine(a == b);                 // same data
Console.WriteLine(ReferenceEquals(a, b));  // but two objects
Console.WriteLine(moved);

var (x, y) = moved;                        // deconstruction
Console.WriteLine($"x={x}, y={y}");

var size = new Size(3, 4);
var copy = size;
copy.Width = 10;                           // record struct: a copy, and mutable
Console.WriteLine(size);

record Point(int X, int Y);
record struct Size(int Width, int Height);

Output:

True
False
Point { X = 5, Y = 2 }
x=5, y=2
Size { Width = 3, Height = 4 }

Choosing a Kind of Type

KindSemanticsEquality by defaultTypical use
classreferenceidentity (same object)entities with behaviour and state: services, accounts, UI elements
structvaluefield by field (slow, reflection-based unless overridden)small number-like values; performance-critical code
recordreferencevalue (generated)immutable data: DTOs, messages, results
record structvaluevalue (generated)small data values that need equality and a nice ToString

Arrays & Collections

When you need many values of the same type, use a collection. Every collection below is generic: the element type goes in angle brackets, and the compiler rejects anything else.

Arrays

An array has a fixed length chosen when it is created, and its elements are stored next to each other in memory, which makes indexing very fast. C# has three shapes: one-dimensional int[], rectangular int[,] (a true grid) and jagged int[][] (an array of arrays whose rows may differ in length). Indexes start at 0; ^1 counts from the end, and a range a..b takes a slice from a up to, but not including, b.

// One-dimensional, rectangular and jagged arrays; indexes from the end and ranges.
int[] scores = { 90, 75, 88 };
Array.Sort(scores);
Console.WriteLine(string.Join(", ", scores));

int[,] grid = new int[2, 3];          // 2 rows, 3 columns, all zero
grid[1, 2] = 7;
Console.WriteLine($"{grid.GetLength(0)}x{grid.GetLength(1)}, grid[1,2]={grid[1, 2]}");

int[][] jagged = [[1], [2, 3], [4, 5, 6]];   // collection expressions (C# 12)
foreach (int[] row in jagged)
    Console.WriteLine(string.Join(" ", row));

Console.WriteLine(scores[^1]);                    // last element
Console.WriteLine(string.Join(", ", scores[..2])); // first two

Output:

75, 88, 90
2x3, grid[1,2]=7
1
2 3
4 5 6
90
75, 88

List, HashSet and Dictionary

For data whose size changes, use the generic collections in System.Collections.Generic:

  • List<T> — an ordered, resizable array. The default choice.
  • HashSet<T> — unique elements with very fast Contains; order is not meaningful.
  • Dictionary<TKey, TValue> — values looked up by a unique key. Reading a missing key with dict[key] throws a KeyNotFoundException, so use TryGetValue when the key may be absent.
// The three collections you will use most.
var names = new List<string> { "Grace", "Ada", "Linus" };
names.Add("Ada");
names.Sort();
Console.WriteLine(string.Join(", ", names));

var unique = new HashSet<string>(names);       // duplicates are dropped
Console.WriteLine($"{unique.Count} unique, has Ada: {unique.Contains("Ada")}");

var ages = new Dictionary<string, int> { ["Ada"] = 36, ["Grace"] = 85 };
ages["Linus"] = 54;                              // add or replace

if (ages.TryGetValue("Grace", out int age))
    Console.WriteLine($"Grace: {age}");
Console.WriteLine(ages.ContainsKey("Alan"));

foreach (var (name, years) in ages)
    Console.WriteLine($"{name} -> {years}");

Output:

Ada, Ada, Grace, Linus
3 unique, has Ada: True
Grace: 85
False
Ada -> 36
Grace -> 85
Linus -> 54

A Dictionary happens to return items in insertion order while nothing has been removed, but that is not guaranteed. Use SortedDictionary or sort the keys when order matters. The demos 11_lists.cs and 12_dictionaries.cs go further.

Tuples

Named Elements and Deconstruction

A tuple groups a few values without declaring a type, which is ideal for returning more than one result from a method. Name the elements so that callers read result.Min instead of result.Item1, and deconstruct them directly into variables. When a tuple starts travelling across your program, promote it to a record.

// A tuple returns two values from one method without a dedicated type.
var (min, max) = MinMax([4, 9, 1, 7]);
Console.WriteLine($"min={min}, max={max}");

var stats = MinMax([10, 20]);
Console.WriteLine($"{stats.Min}..{stats.Max}");

static (int Min, int Max) MinMax(int[] values) => (values.Min(), values.Max());

Output:

min=1, max=9
10..20

Practice

Exercises

  1. Change MoveStruct to take ref PointStruct s and call it with MoveStruct(ref a). What does the program print now?
  2. Rewrite Money as a readonly record struct and compare the amount of code. Make Add throw when the currencies differ.
  3. Count how often each word occurs in a sentence with a Dictionary<string, int>, then print the words sorted by count.
  4. Store a 3×3 tic-tac-toe board in a char[,] and write a method that returns the winner, or ' ' when there is none.