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

preview_player
Показать описание

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

Learn more from video courses:

Other videos on this channel you may be interested in watching:
Рекомендации по теме
Комментарии
Автор

I've been a fan of Zoran's Pluralsight and Udemy courses for ... a decade? A long time. IMO, he's the best at what he does.

scott
Автор

Zoran - you are just brilliant! Thanks for showing us the use cases for required vs. init, the [SetRequiredMembers] attribute which I'd not heard of, and how copy constructors along with initialisers are used in a consistent way under a functional programming paradigm. Cheers

ChrisWalshZX
Автор

This channel deserves more subscribers, I hope that with time it will grow much more because your lessons are very valuable for everyone.

kristianaranda
Автор

Another amazing video. I would encourage everybody to subscribe to this channel and also take Zoran's courses on Udemy and PluralSight.

obinnaokafor
Автор

What is the difference between required keywork and ! after the type?

martinlopezrubio
Автор

The [SetsRequiredMembers] attribute puzzles me - I expect the C# compiler can figure this out in the same way that it figures out how a constructor has neglected to initialize any non-nullable member. Why the difference?

kenbrady