Working with records
Before we dive into the new records language feature, let us see some other related new features of 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 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
PacktLibraryNetStandard2
project/folder, 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? FirstName { get; init; } public string? LastName { get; init; } }
- In
Program.cs
, add statements to instantiate a new immutable person and then try to change one...