Using Struct Default Values In .NET 7

Introduction

Microsoft has just released .NET 7 on 14th November 2022. In the previous articles, we looked at some of the new features.

Today, we will look at another feature introduced with .NET 7 and that is the new Struct Default Values. Let us begin.

The Struct default value

Let us create a console application using Visual Studio 2022 Community edition.

Struct Default Values in .NET 7

Struct Default Values in .NET 7

Now, add the below code to the “Program.cs” file:

Employee employee = new(100, "John Smith", "Test Address");
Console.WriteLine($ "Employee Id={employee.Id}, Name={employee.Name}, Address={employee.Address}");
public struct Employee {
    public int Id;
    public string Name;
    public string Address;
    public Employee(int id, string name, string address) {
        Id = id;
        Name = name;
    }
}

When we run the application, we see the below,

Struct Default Values in .NET 7

Hence, in .NET 7/ C#11, we can declare a struct constructor which does not set all values passed in it. In the above code, the “Address” although passed is not set and is null. This was not possible with earlier versions of C#.

Summary

In this article we looked at a new feature that has been introduced with .NET 7. Using the default struct value feature offers us flexibility not available in earlier versions of C#. In the next article, we will look into another feature of .NET 7.