DEV Community

Wriju's Blog
Wriju's Blog

Posted on • Updated on

C# 9.0 Value-based Equality

Object class comes with two static methods, Equals and ReferenceEquals. record overrides this to check the equality of values one by one recursively. That means even if for two different record objects having same set of properties and the values will be equal.

public record Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

For two different objects with different property values,

//A developer
var developer = new Employee() { FirstName = "Wriju", LastName = "Ghosh" };
//an intern
var juniordev = developer with { FirstName = "Wrishika" };

Console.WriteLine("First Name is different");
Console.WriteLine("=======================");
Console.WriteLine("Reference Equal : {0}",ReferenceEquals(developer, juniordev)); //False
Console.WriteLine("Equals : {0}",Equals(developer, juniordev)); //False
Enter fullscreen mode Exit fullscreen mode

If we create one more record with same property value,

//Junior dev gets a promotion and name changed and matches with the senior dev
var seniordev = juniordev with { FirstName = "Wriju" };
Console.WriteLine("First Name is same");
Console.WriteLine("=======================");
Console.WriteLine("Reference Equal : {0}", ReferenceEquals(developer, seniordev)); //False
Console.WriteLine("Equals : {0}", Equals(developer, seniordev)); //True

Enter fullscreen mode Exit fullscreen mode

Discussion (0)