DEV Community

Wriju's Blog
Wriju's Blog

Posted on • Edited on

5 1

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more