Skip to content
Vignesh Blog
Go back

What I like in c# records

Table of contents

Open Table of contents

Intro

C# records are a modifier and have a lot of built-in functionality for handling data, in this article I’ll be explaining the features that I like and use the most.

Value equality

In the past, for data object comparison, I used to implement IEquatable in my classes for equality; without it, comparisons would be by reference rather than by value.

E.g: In the example, we implement the IEquatable interface and define the implementation of Equals to specify how to compare equality.


public class Employee : IEquatable<Employee>
{
 public string FirstName { get; }

 public string LastName { get; }

 public Employee(string firstName, string lastName)
 {
 FirstName = firstName;
 LastName = lastName;
 }

 public bool Equals(Employee? other)
 {
 return this.FirstName.Equals(other?.FirstName) && this.LastName.Equals(other?.LastName);
 }
}

This may look simple for a few properties, but it does not scale well for more properties. Also, keep in mind we need to handle the hash code as well, which I didn’t cover in the above example, and that leads to a lot of boilerplate code.

See the implementation in record: we have created a Person object which holds two values and, without the need to implement IEquatable, the record handles that for us.

public record Person(string FirstName, string LastName);

var person1 = new Person("John", "Doe");

var person2 = new Person("John", "Doe");

Console.WriteLine(person1 == person2); // Output: True

Built-in formatting for display

When we debug, we want to see the values inside data objects. If we use classes, we need to access the properties to print values to the console; however, records have built-in formatting. In the example below, you can see the Person object has been formatted in a readable way.


Console.WriteLine(person2); //Person { FirstName = John, LastName = Doe }

Nondestructive mutation

If we need to copy an object — say you want to create another person with a different LastName — we can easily do that using the with expression, which performs a shallow copy. This makes our job easy and convenient


Person person3 = person2 with { LastName = "Wick" }
//Person { FirstName = John, LastName = Wick }

Conclusion

I’ve written down the features that I like; there are many more features available, feel free to refer to the official documentation


Share this post:

Previous Post
Using human in the loop in AI application
Next Post
Azure tables in Entity framework pattern