SHARE:

Introducing C#11: Auto Default structs

Introduction

C# 11 improves Structs compared to C# 10 (and earlier). Before C# 11, every Struct properties in the constructor had to be initialized or risk a compilation error. C# 11 fixes that and we will see how in this post.

Example of Auto Default Structs

Consider the following code:

As you can see the CategoryId property is not initialized in the constructor. With previous version of C# 11, it leads to the following compilation error:

“Error  CS0171 Field ‘Product.CategoryId’ must be fully assigned before control is returned to the caller.”

With C# 11, it automatically (behind the scene), assign the default value for a certain type. In our case, it’s an integer and its default value is zero (0).

Demo

The code above give the following according to the new Structs behavior in C# 11:

The CategoryId property has bee initialized to zero (0) as expected.

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.