Working with records
Before we dive into the new records language feature of C# 9 and later, let us see some other related new features.
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 they can be set during instantiation but not after. The new init
keyword enables this. It can be used in place of the set
keyword:
- In the
PacktLibraryModern
project/folder, add a new file namedRecords.cs
. - In
Records.cs
, define an immutable person class, as shown in the following code:namespace Packt.Shared; // C# 10 file-scoped namespace public class ImmutablePerson { public string? FirstName { get; init; } public string? LastName { get; init; } }
- In
Program.cs
, add statements to instantiate a new immutable person and then try to...