IT Trends - HELB

← Back to blog

Published on 2024-10-10 15:15 by Cormontagne Romain

Everything there is to know about the record class


When we create classes in .NET projects, most of them are actually what we could call model types, e.g. classes which are mainly used for data transfer from and to back-end API services, so their role is typically to represent data.

The introduction of the record type

In 2020, with the release of .NET 5, Microsoft has introduced a new record class type, which decreased the typical code developers have to write. Records are defined similarly to classes, the only difference being the keyword : record is used instead of class.

Setting values

When using records, to assign a value to a record, the init keyword is used to replace the classical set. Its behaviour is the same, though it has to follow two rules:

Updating values

If we want to change the values of a record, it is necessary to create a new one. Fortunately, this can be achieved simply by using the with keyword. Here’s a usage example :

var email = "[email protected]";
var id = "12345";
var person = new PersonRecord(email, id)
{
    FirstName = "John"
};
 
person = person with { FirstName = "Jane" };

Equality and comparison

Unlike standard model classes, where it’s crucial to implement the IComparable<T> and IEquatable<T> interfaces and override the equality operators, with record types, these methods are generated automatically.

Hashing and ToString()

With record types, the GetHashCode() method, which is oftentimes daunting to implement, is generated by the compiler, which frees the developer from maintenance concerns.

The ToString method is also unnecessary to implement in most cases with the record types, the exception being if it contains other object types as attributes, such as collections, for instance.

Performance Considerations

Here, we will compare the performance of record types compared to other types in several typical operations. Several benchmarks have been established to highlight the speed of the operations on reference types, value types and records.

Sources

Written by Cormontagne Romain

← Back to blog