0
0
C Sharp (C#)programming~5 mins

Value equality in records in C Sharp (C#)

Choose your learning style9 modes available
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.
When you want to compare two objects based on their data, like two people with the same name and age.
When you need to use objects as keys in collections and want them to be considered equal if their data matches.
When you want simpler code for comparing complex data without writing extra methods.
When you want to avoid bugs caused by comparing object references instead of their values.
Syntax
C Sharp (C#)
public record Person(string Name, int Age);
Records automatically provide value equality, so two records with the same data are equal.
You don't need to override Equals or GetHashCode for records to compare by value.
Examples
Two records with the same data are equal using == operator.
C Sharp (C#)
public record Person(string Name, int Age);

var person1 = new Person("Alice", 30);
var person2 = new Person("Alice", 30);

bool areEqual = person1 == person2;  // true
Records with different data are not equal.
C Sharp (C#)
public record Person(string Name, int Age);

var person1 = new Person("Bob", 25);
var person2 = new Person("Bob", 26);

bool areEqual = person1 == person2;  // false
Using 'with' creates a new record with some changed data, affecting equality.
C Sharp (C#)
public record Person(string Name, int Age);

var person1 = new Person("Carol", 40);
var person2 = person1 with { Age = 41 };

bool areEqual = person1 == person2;  // false
Sample Program
This program shows that two records with the same data are equal, but different data means not equal.
C Sharp (C#)
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
    }
}
OutputSuccess
Important Notes
Value equality means two objects are equal if their data is equal, not just if they are the same object in memory.
Records make it easy to compare data without extra code.
You can still use 'with' expressions to create new records with some changes.
Summary
Records compare objects by their data automatically.
Use records to simplify equality checks in your programs.
Two records with the same values are equal, even if they are different objects.