Required properties in C# is a feature I have secretly wanted for as long as I can remember. It’s finally here in .NET 7 and C# 11. It is important to know that C# 11 will only work in .NET 7. The sample code below was written using .NET 7 and C# 11.
Note what you were looking for. Try these links instead.
- Rate Limiting in .NET 7
- Static Abstract Interface Members in C#11
- Installing Visual Studio Code on Linux
Required Properties in C# in Action
Getting started with required properties in C# will require that you use .NET 7 and C# 11. The code example below was written using Visual Studio for Mac version 17.4.
namespace RequiredProperties;
public class SalesOrder
{
public string OrderNumber { get; set; }
public string OrderStatus { get; set; }
}
As you can see, we have a simple sales order class with two properties for the sales order number and the sales order status.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
Looking at the project file, you will see that we have enabled nullable reference types by setting the Nullable
element to enable
. This came in .NET 6 with C# 10 and can be set to one of four values, namely:
- enable
- disable
- warnings
- annotations
To learn more about these nullable contexts, look at the Microsoft documentation on nullable contexts.
Using Required Properties in C#
Looking at the class we created, you will notice that Visual Studio is telling us that these properties could be null.
We could go ahead and mark the properties as nullable by adding ?
after the string
as follows: public string? OrderNumber { get; set; }
You can also specify a constructor and set those properties at that time. If, however, I want to pass the responsibility of providing values for those properties off to the code calling this class, I can make these properties required.
namespace RequiredProperties;
public class SalesOrder
{
public required string OrderNumber { get; set; }
public required string OrderStatus { get; set; }
}
Required properties in C# allow me to tell the compiler that these properties must be set to a value. I, however, do not have to provide this implementation in my class. I can therefore pass off the responsibility to the code calling my class, as seen in the listing below.
SalesOrder so = new() { OrderNumber = "ABC-123", OrderStatus = "Open" };
This is not production-ready code but only illustrates the point of required properties in C#. This is a welcome addition to C# and will allow developers more flexibility when using classes.