Skip to content

Instantly share code, notes, and snippets.

@karenpayneoregon
Created December 11, 2025 13:36
Show Gist options
  • Select an option

  • Save karenpayneoregon/b67cac5cbbd9ce899d322e097098c8e7 to your computer and use it in GitHub Desktop.

Select an option

Save karenpayneoregon/b67cac5cbbd9ce899d322e097098c8e7 to your computer and use it in GitHub Desktop.
SetsRequiredMembers

Details

The [SetsRequiredMembers] attribute in C# is a compiler-interpreted attribute used to inform the compiler that a specific constructor (or a method group for a primary constructor) is responsible for initializing all members marked with the required modifier.

Purpose and Usage

Introduced in C# 11, the required keyword forces callers to initialize a property or field during object creation, typically through an object initializer. By default, the compiler enforces this rule for all constructors unless the constructor is explicitly decorated with [SetsRequiredMembers].

Applying this attribute to a constructor tells the compiler to disable its checks for object initializers when that constructor is invoked, essentially asserting that all required members will be set as part of that constructor's logic.

[method: SetsRequiredMembers]
public record Person(string FirstName, string LastName, DateOnly BirthDate)
{
public int Id { get; set; }
public required string FirstName { get; set; } = FirstName;
public required string LastName { get; set; } = LastName;
public required DateOnly BirthDate { get; set; } = BirthDate;
}
using System.Diagnostics.CodeAnalysis;
public class Person
{
public int Id { get; set; }
public required string FirstName { get; set; }
public required string LastName { get; set; }
public required DateOnly BirthDate { get; set; }
public Person() { }
[SetsRequiredMembers]
public Person(string firstName, string lastName, DateOnly birthDate)
{
FirstName = firstName;
LastName = lastName;
BirthDate = birthDate;
}
}
internal partial class Program
{
static void Main(string[] args)
{
Person person1 = new()
{
FirstName = "Jane",
LastName = "Doe",
BirthDate = new DateOnly(1990, 5, 15)
};
Person person2 = new("John", "Smith", new DateOnly(1985, 10, 25));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment