Search⌘ K
AI Features

Properties to Be Set During Instantiation and Defining Indexers

Explore how to use the required modifier in C# 11 to enforce property initialization during object instantiation. Understand defining indexers to access object elements using array-like syntax, enabling cleaner manipulation of custom types in OOP.

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:

C#
namespace Packt.Shared;
public class Book
{
// Needs .NET 7 or later as well as C# 11 or later.
public required string? Isbn { get; set; }
public required string? Title { get; set; }
public string? Author { get; set; }
public int PageCount { get; set; }
}

Note: All ...