-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Closed
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Runtime.CompilerServices
Milestone
Description
Background and motivation
As part of supporting C# 11's Required Members feature, we need two new attributes: RequiredMemberAttribute and NoRequiredMembersAttribute. They work as follows:
RequiredMemberAttributewill be applied to every type (class or struct) that defines required members, and to all the members (fields or properties) that are required by that type.NoRequiredMembersAttributewill be applied to a constructor of a type that has required members, and then users of that constructor will not be required to set any members of the type when calling it. Think copy constructors for records: this is how they will communicate that calling the constructor does not require setting any members, because all members will have been set by the copy constructor itself.
API Proposal
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Field | AttributeTargets.Property)]
public sealed class RequiredMemberAttribute : Attribute { }
}
namespace System.Diagnostics.CodeAnalysis
{
[AttributeUsage(AttributeTargets.Constructor)]
public sealed class NoRequiredMembersAttribute : Attribute { }
}API Usage
RequiredMemberAttribute will not be manually usable. It will be an error to apply it to C# code by hand.
A copy constructor for a type that has required members might look like this:
public class C
{
public required int Property { get; init; }
public C() {}
[NoRequiredMembers]
public C(C c) => this.Property = c.Property;
}
// Usage
var c1 = new C { Property = 1 };
var c2 = new C(c1); // No error, constructor waives requirementsAlternative Designs
I am open to alternative naming schemes. We had also considered a version of RequiredMemberAttribute where all the members were listed by name as a string argument to the constructor, but we redesigned after some community feedback and consultation with Wrighton to make sure that more attributes wouldn't break perf.
Risks
No response
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
api-approvedAPI was approved in API review, it can be implementedAPI was approved in API review, it can be implementedarea-System.Runtime.CompilerServices