Properties to Be Set During Instantiation and Defining Indexers

Learn about the properties to be set during instantiation and utilizing indexers for simplified data access.

Properties to be set during instantiation

C# 11 introduces the required modifier. If we use it on a property or field, the compiler will ensure that we set the property or field to a value when we instantiate it. It requires targeting .NET 7 or later, so we need to create a new class library first:

Step 1: In the Chapter05 solution or workspace, add a new class library project PacktLibraryModern that targets .NET 7.0.

Step 2: In the PacktLibraryModern project, add a new class file named Book.cs.

Step 3: Modify the class to give it four properties with two set as required, as shown in the following code:

Get hands-on with 1400+ tech skills courses.