Skip to content

[API Proposal]: RequiredMemberAttribute and NoRequiredMembersAttribute #64248

@333fred

Description

@333fred

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:

  • RequiredMemberAttribute will 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.
  • NoRequiredMembersAttribute will 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 requirements

Alternative 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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions