C# – First steps with C# and .NET – part 033.

Many of the C# classes created today are simply collections of data to be transferred from one place to another.
C# 9 introduces records, a new reference type that you can create instead of classes or structs. Records are distinct from classes in that record types use value-based equality. , see the official website.
Records have a few important behaviours:

  • they are immutable;
  • they are comparable to other records through value equality by default;
  • they support non-destructive mutation through a new “with” keyword;
  • they generates automatic deconstructors to match their primary constructors.

Let’s see a simple example.
First create a folder and create a new proiect:

The source code is this:

You can see how the Person class is replaced by a record:

You can inherit this class and use it as other classes

You can also see a pattern matching mode involving an old keyword, if, and a new keyword, is.
After running the program I got this output:

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.