Code inspection: Redundant attribute [SetsRequiredMembers]
The [SetsRequiredMembers] attribute, introduced in C# 11, is used to indicate that a constructor fully initializes all required members in a type. Required members are marked using the required modifier, ensuring that they must be set before an object is fully constructed. For example:
public class ExampleClass
{
public required string Name { get; init; }
public required int Age { get; init; }
[SetsRequiredMembers]
public ExampleClass(string name, int age)
{
Name = name;
Age = age;
}
}
This inspection reports cases where the [SetsRequiredMembers] attribute applied to a constructor is redundant. This can occur when the class has no required members or when a base constructor already satisfies the initialization of required members.
public class Example
{
[SetsRequiredMembers] // Redundant: No required members in the class
public Example() { }
}
public class Example
{
public Example() { }
}
Removing redundant [SetsRequiredMembers] attributes keeps the code concise and avoids unnecessary ambiguity.
11 July 2025