Structs: value semantics & immutability pattern
Understand struct value semantics in C# 6 and build an immutable struct pattern (copy-on-change).
Structs overview
Goal: Use structs safely.
- Value semantics (copy on assign)
- Immutable-struct pattern in C# 6
- Passing by value vs by ref
- Boxing note
Copy semantics
Structs are value types: assignment makes a copy. Changing the copy does not change the original.
using System;
// Simple struct with public fields for demo (okay for small POD data)
public struct Point
{
public int X;
public int Y;
}
public class Program
{
public static void Main(string[] args)
{
Point a = new Point();
a.X = 1; a.Y = 2;
Point b = a; // copy the value
b.X = 9; // change the copy
Console.WriteLine("a=(" + a.X + "," + a.Y + ")");
Console.WriteLine("b=(" + b.X + "," + b.Y + ")"); // different from a
}
}
All lessons in this course
- Structs: value semantics & immutability pattern
- Record-like types & value-based equality (pattern)
- Enums & [Flags]