Working with records
Before we dive into the new records language feature of C# 9, 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
PacktLibrary9
folder, add a new file namedRecords.cs
. - In the
Records.cs
file, define an immutable person class, 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
, at the bottom of theMain
method, add statements to instantiate a new immutable person and then try to change...