C# Tip: Use required members to prevent invalid object initialization (beware of SetsRequiredMembers attribute!)
Just a second! π«·
If you are here, it means that you are a software developer. So, you know that storage, networking, and domain management have a cost .
If you want to support this blog, please ensure that you have disabled the adblocker for this site. I configured Google AdSense to show as few ADS as possible - I don't want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.
Thank you for your understanding.
- Davide
Sometimes we create objects that technically compile, but they are missing critical data.
For example, in a board game catalog you might create a BoardGame without Name or MinPlayers, and only discover the problem later at runtime.
This is where the required keyword in C# comes to the rescue: it helps you enforce that certain properties must be initialized, and the compiler will raise an error you if they are not.
required was introduced in C# 11 (for example, via the .NET 7 SDK), so make sure your project is using C# 11+.
A common problem: half-initialized objects
Imagine this simple data model:
public class BoardGame
{
public string? Name { get; init; }
public int MinPlayers { get; init; }
public int MaxPlayers { get; init; }
}
BoardGame game = new();
This compiles, but game is not usable in practice, as all its properties are null or empty (or set to the default value).
Now let’s make the critical properties required.
Use Required keyword to force initialization
Let’s mark the Name and MinPlayers as required:
public class BoardGame
{
public required string Name { get; init; }
public required int MinPlayers { get; init; }
public int MaxPlayers { get; init; }
public int SuggestedAge { get; init; } = 10;
}
Now, if you forget even one required member, the compiler reports an error.
This is what happens if you try to create a BoardGame without initializing any required property:
BoardGame game = new(); // Compiler error!
Required member ‘X’ must be set in the object initializer or attribute constructor.

You must initialize all required properties, either via object initializer syntax or via a constructor.
BoardGame game = new BoardGame
{
Name = "Dixit",
MinPlayers = 3,
MaxPlayers = 8
};
Having required members means that you can no longer create half-initialized objects, and the compiler will help you enforce that. And, in turn, this leads to better code quality, fewer defensive checks sprinkled around your codebase, and fewer runtime errors.
Required keyword vs Constructor initialization: when to use what
To enforce required properties, you can either use the required keyword.
public class BoardGame
{
public required string Name { get; init; }
public required int MinPlayers { get; init; }
public required int MaxPlayers { get; init; }
public int SuggestedAge { get; init; } = 10;
}
Or you can enforce them via constructor parameters:
public class BoardGame
{
public string Name { get; init; }
public int MinPlayers { get; init; }
public int MaxPlayers { get; init; }
public int SuggestedAge { get; init; } = 10;
public BoardGame(string name, int minPlayers, int maxPlayers)
{
Name = name;
MinPlayers = minPlayers;
MaxPlayers = maxPlayers;
}
}
Both approaches are valid, but they solve slightly different problems.
- Constructor parameters are great when you want strict positional creation and immediate validation logic.
requiredmembers are great when object initializer syntax improves readability, especially for models with many optional fields.
As a rule of thumb, I usually prefer:
- Constructors for domain invariants that must be validated together: either all properties are valid at the same time, or none of them is and the object cannot be initialized (for example, in a
DateRangeclassStartDatemust always be beforeEndDate. requiredkeyword for mandatory properties that are independent of each other, like aBoardGamewhereName,MinPlayers, andMaxPlayersare all required, but they don’t depend on each other.
The SetsRequiredMembers attribute to annotate constructors that initialize required members
If you populate required properties inside a constructor, you can annotate it with SetsRequiredMembers.
using System.Diagnostics.CodeAnalysis;
public class BoardGame
{
public required string Name { get; init; }
public required int MinPlayers { get; init; }
public required int MaxPlayers { get; init; }
public int SuggestedAge { get; init; } = 10;
[SetsRequiredMembers]
public BoardGame(string name, int minPlayers, int maxPlayers)
{
Name = name;
MinPlayers = minPlayers;
MaxPlayers = maxPlayers;
}
}
BoardGame azul = new("Azul", 2, 4);
This attribute tells the compiler: Β«Trust me, this constructor initializes all required members.Β»
Use it carefully: if you forget one required property inside the constructor, the compiler will not notice it, and therefore it will not protect you the same way object initializers do.
Have a look at this example:
public class BoardGame
{
public required string Name { get; init; }
public required int MinPlayers { get; init; }
public required int MaxPlayers { get; init; }
public int SuggestedAge { get; init; } = 10;
[SetsRequiredMembers]
public BoardGame(string name )
{
Name = name;
}
}
As you can see, we have three required properties (Name, MinPlayers, MaxPlayers) but the constructor only initializes one of them. The compiler will not complain, and you can create a BoardGame instance like this:
BoardGame azul = new("Azul");
So, yeah, the SetsRequiredMembers attribute is a great tool, but it requires discipline and careful usage.
A tiny checklist before adopting required members
Before adding required everywhere, ask yourself:
- Is this value truly mandatory for every valid instance?
- Do serializers or mappers in your project support this pattern correctly?
If the answer is “yes”, required members are usually a great upgrade.
Further readings
As always, check the official documentation for more details on required members and related topics.
π required modifier (C# reference) | Microsoft Learn
π init keyword (C# reference) | Microsoft Learn
π SetsRequiredMembersAttribute API reference | Microsoft Learn
This article first appeared on Code4IT π§
We saw that you can enrich a constructor using SetsRequiredMembers attribute, to tell the compiler that all required members are initialized inside the constructor. But… what is an attribute? How can you create your own attributes? Check out my article on custom attributes in C# to learn more.
π C# Tip: How to create Custom Attributes, and why they are useful | Code4IT
Wrapping up
Required members are a simple but powerful way to make invalid states harder to represent.
You keep the readability of object initializers, while getting compile-time safety for critical fields.
Do you prefer constructors, required members, or a mix of both for your domain models?
I hope you enjoyed this article! Let's keep in touch on LinkedIn, Twitter or BlueSky! π€π€
Happy coding!
π§