New C# 11 Keyword – required – and How To Use It Right



The ‘required’ keyword, introduced in C# 11, is completing the cycle started in C# 9, when init-only setters were introduced. By combining object initializers with required properties, we can redefine the process of instantiating classes.
A required member must be initialized at the time of construction. Failing to do so will cause a compile-time error, because compiler is performing due diligence on every instantiation of an object which declares required members.
Special attention is paid to constructors. Every constructor that sets all required members – fields or properties – must be adorned with the SetsRequiredMembers attribute. That is the signal to the constructor that a use of that constructor is safe, from perspective of the required members. If this attribute is not set, then the constructor would expect all required members to be set using the initializer right after the call to the constructor.
It is important to note that there is no “middle ground”. A constructor is either considered to set all required members, or all required members must appear in the initializer, regardless of what the constructor actually does.

Chapters:
00:00 Intro
00:31 Initializing properties before C# 11
03:02 Using the required keyword in C# 11
04:09 Using the SetsRequiredMembers attribute
06:07 Using required properties in nondestructive mutation

Video courses:
Beginning Object-oriented Programming with C# ► https://codinghelmet.com/go/beginning-oop-with-csharp
Collections and Generics in C# ► https://codinghelmet.com/go/collections-and-generics-in-cs
Making Your C# Code More Object-oriented ► https://codinghelmet.com/go/making-your-cs-code-more-oo

Other courses at Pluralsight ► https://codinghelmet.com/go/pluralsight
Other courses at Udemy ► https://codinghelmet.com/go/udemy

Additional videos:
The Fastest Way to Modify a List in C# ► https://youtu.be/0oSN65eM-tc
Coding with GitHub Copilot – Beginner to Master ► https://youtu.be/B9DKv09IfT4
Want to Start with DDD? Try Ubiquitous Language First! ► https://youtu.be/_zWMjMUHinc
Using C# Record Types ► https://youtu.be/VouNkrgkH78
Covariance and Contravariance in C# ► https://youtu.be/Wp5iYQqHspg
How do Virtual Functions Work? ► https://youtu.be/b0IDTWoaUJ0

Practical Design playlist at YouTube ► https://youtube.com/playlist?list=PLSDYwLgFqaX78eEg_YKs0wHmOMi7_ggZr

Comments are closed.