Skip to content

Primary Constructor as an attribute target #53684

@RexJaeschke

Description

@RexJaeschke

Type of issue

Missing information

Description

[The following applies to the section "Attribute targets." I'm not sure this is the best place to add my proposed text, but it's a good start!]

I'm writing feature proposals for the Ecma C# standard for record classes (V9), record structs (V10), and primary constructors (V12). Consider the following example, which requires V12:

[AttributeUsage(AttributeTargets.Constructor)]
public class Attr1 : Attribute { }

[method: Attr1]
record C(int X, int Y);

To apply an attribute to a primary constructor, one must use the non-intuitive target method (as shown above), as C# does not define a target constructor. However, the library allows one to distinguish between a method and a constructor, so one must use AttributeTargets.Constructor and not AttributeTargets.Method in the attribute's definition.

The table in this help section has the following row:

method Method or get and set property accessors

Add to this something like "; also can be applied to a class or struct having a primary constructor, in which case it applies to that constructor."

Separately, staring with V9, attributes are also allowed on the fields and associated properties that are auto-generated for records. Consider the following:

[AttributeUsage(AttributeTargets.Property)]
public class Attr2 : Attribute { }
[AttributeUsage(AttributeTargets.Field)] 
public class Attr3 : Attribute { }

record S([property: Attr2] int X, [field: Attr3] int Y);

There are no surprises here, but it likely is worth stating somewhere that one can have attributes on primary constructor parameters of a target type other than parameter in order to annotate the underlying fields and properties.

Page URL

https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/reflection-and-attributes/

Content source URL

https://github.com/dotnet/docs/blob/main/docs/csharp/advanced-topics/reflection-and-attributes/index.md

Document Version Independent Id

1b8ea375-81a3-caef-f51a-f08635c6610a

Platform Id

ed242b50-e0ff-63ca-afef-d29db206a14c

Article author

@BillWagner

Metadata

  • ID: c8bc41f1-c2f4-3d82-d65b-e986735162bd
  • PlatformId: ed242b50-e0ff-63ca-afef-d29db206a14c
  • Service: dotnet-csharp
  • Sub-service: advanced-concepts

Related Issues

Metadata

Metadata

Assignees

Type

No type
No fields configured for issues without a type.

Projects

Status

🔖 Ready

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions