...
/Properties to Be Set During Instantiation and Defining Indexers
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.
We'll cover the following...
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:
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 three string properties are nullable. Setting a required property or field ...