6

Introducing C#11: Required properties

 1 year ago
source link: https://anthonygiretti.com/2022/12/02/introducing-c11-required-properties/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Introducing C#11: Required properties

2022-12-02 by anthonygiretti

Introduction

C# 11 improves the initialization of objects and struct. Marking one or more properties as mandatory on initialization is now possible and will help you not to forget to initialize your properties correctly. In this post I will show you how it works with the object initializer syntax and the object instantiation with a constructor.

Required properties in practical

Marking properties as required requites to add the required keyword on your properties as follow:

When initializing a car object, if you miss initializing a property, for example, the BrandId property, the compiler will raise the following error:

“Error CS9035 Required member ‘Car.BrandId’ must be set in the object initializer or attribute constructor.”

Using a constructor will lead to the same error if you don’t initialize all required properties. Otherwise, if you do not voluntarily initialize your required properties you will have to decorate your class with the SetsRequiredMembers attribute to avoid any compilation error, Examples:

Isn’t practical? 🙂 . I hope you won’t forget anymore your properties !

Like this:

Loading...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK