Working with Records

Learn about C# 9 features, including init-only properties and records, which enhance immutability and object manipulation capabilities.

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

We have used object initialization syntax to instantiate objects and set initial properties. Those properties can also be changed after instantiation. Sometimes, we want to treat properties like read-only 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:

Step 1: In the PacktLibraryNetStandard2 project or folder, add a new file named Records.cs.

Step 2: In Records.cs, define a person class with two immutable properties, as shown in the following code:

Get hands-on with 1400+ tech skills courses.