Value equality in C# 9.0 compares records and declares them equal if the values and types of the properties and fields are equal. Equality for other reference types is when the variables refer to the same object.
The class method in C# 9.0 comes with two inbuilt methods, Equals
and ReferenceEquals
. ReferenceEquals
checks whether two objects are the same instance. Records override equality methods and operators. This can be done manually with simple classes, but it is best to use records to avoid bugs when the properties and fields of the class are changed.
The following example demonstrates the use of value equality in C# 9.0:
The program creates a record Person
and sets its fields to identical values. The ==
operator returns true because all the fields of the two objects have identical values, but ReferenceEquals
returns false because the two objects are not the same instance.
The ==
operator on the two objects of class Employee
return false despite having identical field values and types.
using System;public class Program{public record Person(string FirstName, string LastName);public class Employee{public string FirstName { get; init; }public string LastName { get; init; }}public static void Main(){// create two objects of PersonPerson person1 = new("Sam", "Johnson");Person person2 = new("Sam", "Johnson");//check equalityConsole.WriteLine("Value Equality of the record Person:");Console.WriteLine(person1 == person2);Console.WriteLine("Reference Equality of the record Person:");Console.WriteLine(ReferenceEquals(person1, person2));// create two object of EmployeeEmployee employee1 = new Employee {FirstName = "Sam", LastName = "Johnson"};Employee employee2 = new Employee {FirstName = "Sam", LastName = "Johnson"};// check reference equalityConsole.WriteLine("Equality of the class Employee:");Console.WriteLine(employee1 == employee2);Console.WriteLine("Reference Equality of the class Employee:");Console.WriteLine(ReferenceEquals(employee1, employee2));}}
Value Equality of the record Person:
True
Reference Equality of the record Person:
False
Equality of the class Employee:
False
Reference Equality of the class Employee:
False
Free Resources