Using The New Required Keyword 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 "required" keyword. Let us begin.

The required keyword

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

Using The New Required Keyword In .NET 7

Using The New Required Keyword In .NET 7

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

var employee = new Employee {
    Id = 1
};
var student = new Student();
class Employee {
    public int Id {
        get;
        init;
    }
    public required string Name {
        get;
        init;
    }
}
class Student {
    public int Id {
        get;
        set;
    }
    public required string Name {
        get;
        set;
    }
}

Here, we see that we have created two classes and have defined the property "Name" with the new "required" keyword. This means that this property is mandatory for this class. If we do not add it and try to compile the code, we get the below,

Using The New Required Keyword In .NET 7

 Now, change the code to the below,

using System.Diagnostics.CodeAnalysis;
var employee = new Employee {
    Id = 1, Name = "Munib Butt"
};
var student = new Student(1, "Munib Butt");
class Employee {
    public int Id {
        get;
        init;
    }
    public required string Name {
        get;
        init;
    }
}
class Student {
    public int Id {
        get;
        set;
    }
    public required string Name {
        get;
        set;
    }
    [SetsRequiredMembers]
    public Student(int id, string name) {
        Id = id;
        Name = name;
    }
}

All compiles fine. Hence, the properties defined as "required" need to be defined in the object initializer or attribute constructor otherwise the code does not compile. This feature is very useful for adding properties that are required.

Summary

In this article, we looked at a new feature that has been introduced with .NET 7. Using the required keyword in classes helps us ensure that required properties are defined. In the next article, we will look into another feature of .NET 7.