C# Record

After .net 5 came up, a new C# 9 mechanism called Record has drawn C# developer much attention. Record has both Reference Type and Value Type features. It is used to store data like struct, however as it is Reference Type, it has behaviors like encapsulate and inheritance. Hence we can use record to store DTO data. This article will introduce record feature.

Employee inherit Person record

In C# 9, we just have to write a single new word to initialize record or class variable. As you can see is that Person record only contains data, which is like struct. Employee also has Person same attributes like Name and Age. Therefore, Employee inherits from Person. we can use Person and Employee record to have both class and struct functions.

The output is shown below

When we compare two Record type variable, it uses value type to compare. Person josh and joshSecond has same attributes’ value, so the compare result is true. Nevertheless, record is reference type, so when we use object.ReferenceEquals, the result returns to false.

What is the output of ToString()?

The output is

with-expression

when we want to change record variable value, we will realize that we can’t because record is immutable.

This is the time we use with-expression

Before we can use struct to store data as it occupies less memory size than class. However, struct does not have some reference type behaviors, in so scenarios the developers will have to decide which variable type to use to store data. Record solves this problems and it gives the developer an optimal choice to select.