Value Equality & Deconstruction
Understand record structural equality, override Equals/GetHashCode, and use deconstruction patterns.
Value Equality & Deconstruction is a free C# Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Record Equality Deep Dive
Records automatically generate Equals, GetHashCode, and operators ==/!= that compare all properties structurally. Understanding how this works helps you use records correctly and override when needed.
How Auto-Generated Equality Works
The compiler generates code that compares each property using EqualityComparer<T>.Default. For reference-type properties, this is their own Equals — not reference equality.
public record Address(string Street, string City);
public record Person(string Name, Address HomeAddress);
var a = new Person("Alice", new Address("123 Main", "NYC"));
var b = new Person("Alice", new Address("123 Main", "NYC"));
Console.WriteLine(a == b); // True — deep structural equality
// Equality checks:
// Name: "Alice" == "Alice" ✓
// HomeAddress: compares Address properties recursively ✓Overriding Generated Equality
You can override Equals and GetHashCode on a record when you want custom equality logic — for example, comparing only a subset of properties.
public record Customer(int Id, string Name, string Email)
{
// Consider customers equal if they have the same ID,
// regardless of name or email changes
public virtual bool Equals(Customer? other)
=> other is not null && Id == other.Id;
public override int GetHashCode() => Id.GetHashCode();
}Records in Collections
Because records implement IEquatable<T> with structural equality, they work correctly as dictionary keys, in HashSets, and with LINQ's Distinct and GroupBy.
public record Tag(string Name, string Color);
var tags = new List<Tag>
{
new("C#", "blue"), new("C#", "blue"), new("dotnet", "purple")
};
var unique = tags.Distinct().ToList(); // [Tag(C#, blue), Tag(dotnet, purple)]
var set = new HashSet<Tag>(tags);
set.Contains(new Tag("C#", "blue")); // trueDeconstruction: The Basics
Positional records automatically generate a Deconstruct method with out parameters for each positional property. This enables tuple-like unpacking.
public record Point(double X, double Y);
public record RGB(byte R, byte G, byte B);
var p = new Point(3.0, 4.0);
var (x, y) = p; // deconstruct
Console.WriteLine($"{x}, {y}");
var color = new RGB(255, 128, 0);
var (r, g, b) = color;
Console.WriteLine($"R={r}, G={g}, B={b}");Deconstruction in Pattern Matching
Records deconstructed in switch expressions enable powerful positional pattern matching.
public record Point(int X, int Y);
string Classify(Point p) => p switch
{
(0, 0) => "Origin",
(int x, 0) => $"X-axis at {x}",
(0, int y) => $"Y-axis at {y}",
(int x, int y) when x == y => $"Diagonal at {x}",
(int x, int y) => $"Point ({x}, {y})"
};
Console.WriteLine(Classify(new Point(0, 0))); // Origin
Console.WriteLine(Classify(new Point(3, 3))); // Diagonal at 3Custom Deconstruct Methods
Non-positional records (and any class) can add a Deconstruct method manually. Extension methods can also add deconstruction to existing types.
public class Temperature
{
public double Celsius { get; }
public Temperature(double c) => Celsius = c;
// Manual Deconstruct
public void Deconstruct(out double celsius, out double fahrenheit)
{
celsius = Celsius;
fahrenheit = Celsius * 9 / 5 + 32;
}
}
var t = new Temperature(100);
var (c, f) = t;
Console.WriteLine($"{c}°C = {f}°F"); // 100°C = 212°FIgnoring Parts of Deconstruction
Use discards (_) to ignore unwanted parts of a deconstruction — similar to tuple discards.
public record Order(int Id, string Customer, decimal Total, DateTime Date);
var order = new Order(42, "Alice", 99.99m, DateTime.UtcNow);
// Only want Id and Total
var (id, _, total, _) = order;
Console.WriteLine($"Order {id}: ${total}");
// In switch: ignore some fields
string Classify(Order o) => o switch
{
(_, _, > 1000, _) => "High value",
(_, _, > 100, _) => "Medium value",
_ => "Low value"
};Property Patterns vs Positional Patterns
Records support both positional patterns (by position) and property patterns (by name). Property patterns are more readable for records with many properties.
public record Order(int Id, string Status, decimal Total);
// Positional pattern:
string DescribePos(Order o) => o switch
{
(_, "Shipped", > 100) => "High-value shipped",
_ => "Other"
};
// Property pattern (more readable):
string DescribeProp(Order o) => o switch
{
{ Status: "Shipped", Total: > 100 } => "High-value shipped",
{ Status: "Cancelled" } => "Cancelled",
_ => "Other"
};Real-World: Result Type Pattern
A discriminated union–style result type using records and deconstruction — a functional approach to error handling.
public abstract record Result<T>;
public record Success<T>(T Value) : Result<T>;
public record Failure<T>(string Error) : Result<T>;
Result<Order> PlaceOrder(CreateOrderRequest req)
{
if (req.Quantity <= 0)
return new Failure<Order>("Quantity must be positive");
var order = CreateOrder(req);
return new Success<Order>(order);
}
// Consuming:
var result = PlaceOrder(request);
switch (result)
{
case Success<Order>(var order):
return Results.Created($"/orders/{order.Id}", order);
case Failure<Order>(var error):
return Results.BadRequest(error);
}Quick Check
What does using a discard (_) in a deconstruction expression do?
Recap: Value Equality & Deconstruction
Key takeaways:
- Auto-generated equality compares all properties structurally, recursively
- Override Equals/GetHashCode on records for custom identity logic
- Records work correctly as HashSet elements and dictionary keys
- Positional records auto-generate Deconstruct — use var (a, b) = record
- Discards (_) ignore unwanted positional values in deconstruction
- Property patterns ({Status: "X"}) are more readable than positional for complex records
Frequently asked questions
Is the “Value Equality & Deconstruction” lesson free?
Yes — the full text of “Value Equality & Deconstruction” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “Value Equality & Deconstruction”?
Understand record structural equality, override Equals/GetHashCode, and use deconstruction patterns. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Value Equality & Deconstruction” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Record Types: Basics & Syntax
- Immutability with init & with
- Value Equality & Deconstruction
- Records in Domain-Driven Design