Introduction
Records in C# help you compare objects by their content, not just by their location in memory. This makes checking if two objects are 'the same' easier and more natural.
public record Person(string Name, int Age);
public record Person(string Name, int Age); var person1 = new Person("Alice", 30); var person2 = new Person("Alice", 30); bool areEqual = person1 == person2; // true
public record Person(string Name, int Age); var person1 = new Person("Bob", 25); var person2 = new Person("Bob", 26); bool areEqual = person1 == person2; // false
public record Person(string Name, int Age); var person1 = new Person("Carol", 40); var person2 = person1 with { Age = 41 }; bool areEqual = person1 == person2; // false
using System; public record Person(string Name, int Age); class Program { static void Main() { var person1 = new Person("Dave", 50); var person2 = new Person("Dave", 50); var person3 = new Person("Eve", 50); Console.WriteLine(person1 == person2); // True Console.WriteLine(person1.Equals(person2)); // True Console.WriteLine(person1 == person3); // False } }
record types in C# regarding equality?record Person(string Name);.record Point(int X, int Y); var p1 = new Point(3, 4); var p2 = new Point(3, 4); Console.WriteLine(p1 == p2);
p1 == p2 compares the data inside the records.True.record Person(string Name);
var p1 = new Person("Alice");
var p2 = new Person("Alice");
if (p1.Equals(p2))
Console.WriteLine("Equal");
else
Console.WriteLine("Not Equal");
p1.Name = "Bob";p1.Name = "Bob"; causes a compile error.Equals is valid and compares values correctly. The semicolon after record declaration is present. Equals returns true because data matches.record Product(int Id, string Name);, how can you create a new record from an existing one but with a different Name while keeping Id the same?var p2 = p1 with { Name = "NewName" }; uses 'with' correctly. Create a new record manually: var p2 = new Product(p1.Name, "NewName"); fails to compile because Id expects int but p1.Name is string. Assign directly: p1.Name = "NewName"; is invalid because record properties are immutable. Use a method to clone and change: var p2 = p1.Clone("NewName"); is invalid as no Clone method exists by default.Pass the test and this pattern moves unknown