Trusted answers to developer questions

What is value equality in C# 9.0?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

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.

Example

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 Person
Person person1 = new("Sam", "Johnson");
Person person2 = new("Sam", "Johnson");
//check equality
Console.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 Employee
Employee employee1 = new Employee {FirstName = "Sam", LastName = "Johnson"};
Employee employee2 = new Employee {FirstName = "Sam", LastName = "Johnson"};
// check reference equality
Console.WriteLine("Equality of the class Employee:");
Console.WriteLine(employee1 == employee2);
Console.WriteLine("Reference Equality of the class Employee:");
Console.WriteLine(ReferenceEquals(employee1, employee2));
}
}

Output

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

RELATED TAGS

c#

CONTRIBUTOR

Ayesha Naeem
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?