Working with record types
Before we dive into the new record language feature, let us see a related keyword, init, introduced with C# 9 and later.
Init-only properties
You have used object initialization syntax to instantiate objects and set initial properties throughout this chapter. Those properties can also be changed after instantiation.Sometimes, you want to treat properties like readonly fields so that they can be set during instantiation but not after. In other words, they are immutable. The init keyword enables this. It can be used in place of the set keyword in a property definition.Since this is a language feature not supported by .NET Standard 2.0, we cannot use it in the PacktLibraryNet2 project. We must use it in the modern project:
- In the
PacktLibraryModernproject, add a new file namedRecords.cs. - In
Records.cs, define a person class with two immutable properties, as shown in the following code:
namespace Packt.Shared;
public class ImmutablePerson
{
public string...