Concept Flow - Value equality in records
Create record instance A
Create record instance B
Compare A and B
Return true
This flow shows how two record instances are created and compared by their values, returning true if all properties match.
public record Person(string Name, int Age); var p1 = new Person("Alice", 30); var p2 = new Person("Alice", 30); bool areEqual = p1 == p2; Console.WriteLine(areEqual);
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Create p1 with Name="Alice", Age=30 | p1 = Person(Name="Alice", Age=30) | p1 created |
| 2 | Create p2 with Name="Alice", Age=30 | p2 = Person(Name="Alice", Age=30) | p2 created |
| 3 | Compare p1 == p2 | Compare all properties: Name and Age | True (values equal) |
| 4 | Print areEqual | Output value of areEqual | True |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| p1 | null | Person(Name="Alice", Age=30) | Person(Name="Alice", Age=30) | Person(Name="Alice", Age=30) | Person(Name="Alice", Age=30) |
| p2 | null | null | Person(Name="Alice", Age=30) | Person(Name="Alice", Age=30) | Person(Name="Alice", Age=30) |
| areEqual | undefined | undefined | undefined | True | True |
C# records compare by value, not reference. Use '==' to check if all properties are equal. Records auto-generate equality methods. Different objects with same data are equal. If any property differs, equality is 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