How to use Required keyword for C# 11
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System.Diagnostics.CodeAnalysis;
var book1 = new Book("Jean M Auel", "The Clan of the Cave Bear");
var book2 = new Book
{
Author = "Jean M Auel",
Title = "The Valley of Horses",
};
public class Book
{
public Book()
{
}
[SetsRequiredMembers]
public Book(string author, string title)
{
Author = author;
Title = title;
}
public required string Title { get; set; }
public required string Author { get; set; }
}
Rererences
Required modifier (C# Reference)
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/required