Skip to main content

How to Put an Attribute on a Record's Property with property: in C#

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

In record Book([property: Description("The number of pages")] int Pages);, the attribute goes on the Pages property that the record generates. Without property:, it would go on the constructor's Pages parameter, where code that reads the property never finds it.

One parameter of a positional record turns into more than one thing. Microsoft's reference: When you use the positional syntax for property definition, the compiler creates: among others, A public automatically implemented property for each positional parameter provided in the record declaration and A primary constructor whose parameters match the positional parameters on the record declaration.

So an attribute written on the parameter needs a target that says which of them it's for. The records reference: The property: target indicates that the attribute is applied to the compiler-generated property. Other values are field: to apply the attribute to the field, and param: to apply the attribute to the parameter.

Syntax​

Syntax
record <Name>([property: <Attribute>(<arguments>)] <Type> <Parameter>);
PartWhat it is
property:The target: the property the record generates for this parameter
<Attribute>(<arguments>)The attribute, such as Description("The number of pages")
<Type> <Parameter>The positional parameter, which also becomes a property with the same name

The general form, from the attributes reference, is [target : attribute-list]. The other two targets on a record parameter are param:, the constructor parameter, and field:, the hidden field behind the property. Without a target, the attribute goes on the parameter. The reference: By default, an attribute applies to the element that follows it.

The Example​

A console app called PropertyAttribute declares a Book record with a Title and a number of Pages. It puts a Description attribute on each parameter, one with property: and one without, then reads them back to show where each one went.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n PropertyAttribute
cd PropertyAttribute
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/PropertyAttribute/PropertyAttribute.csproj:
Determining projects to restore...
Restored /Users/you/source/PropertyAttribute/PropertyAttribute.csproj (in 44 ms).
Restore succeeded.

dotnet new console -n PropertyAttribute creates a folder named PropertyAttribute with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or PropertyAttribute.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. The record goes at the end of the file:

Program.cs (the record)
// Title's attribute has no target, so it goes on the constructor parameter.
// Pages's attribute starts with property:, so it goes on the Pages property.
record Book(
[Description("The book's title")] string Title,
[property: Description("The number of pages")] int Pages);

Description comes from System.ComponentModel and holds a piece of text. Title's attribute has no target, and Pages's starts with property:.

At the top of the file, the code that reads the properties:

Program.cs (read the properties)
using System.ComponentModel;
using System.Reflection;

// Read the Description attribute of each property of Book.
foreach (PropertyInfo property in typeof(Book).GetProperties())
{
DescriptionAttribute? attribute = property.GetCustomAttribute<DescriptionAttribute>();
Console.WriteLine($"Property {property.Name}: {attribute?.Description ?? "(none)"}");
}

Code that reads attributes while the program runs uses reflection. The attributes reference: After you associate an attribute with a program entity, you can query the attribute at run time by using a technique called reflection. typeof(Book).GetProperties() Returns all the public properties of the current Type, and GetCustomAttribute<DescriptionAttribute>() returns A custom attribute that matches T, or null if no such attribute is found. For null, ?. and ?? print (none).

Then the same for the constructor's parameters:

Program.cs (read the parameters)
// Read the Description attribute of each parameter of Book's constructor.
ConstructorInfo constructor = typeof(Book).GetConstructors()[0];
foreach (ParameterInfo parameter in constructor.GetParameters())
{
DescriptionAttribute? attribute = parameter.GetCustomAttribute<DescriptionAttribute>();
Console.WriteLine($"Parameter {parameter.Name}: {attribute?.Description ?? "(none)"}");
}

GetConstructors() Returns all the public constructors defined for the current Type. Book has one, with Title and Pages, so [0] is that constructor, and GetParameters() returns its two parameters.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
Property Title: (none)
Property Pages: The number of pages
Parameter Title: The book's title
Parameter Pages: (none)

macOS-style terminal window titled Terminal — PropertyAttribute showing dotnet run printing Property Title: (none), Property Pages: The number of pages, Parameter Title: The book's title and Parameter Pages: (none)

The two attributes landed in different places. Title's, without a target, is on the constructor parameter, so the Title property has none. Pages's, with property:, is on the Pages property, and the parameter has none. Code that reads the properties only finds the second one.

The Complete File​

macOS-style code window titled Program.cs — PropertyAttribute showing a loop that reads the Description attribute of each property of Book, a loop that reads it from each parameter of Book's constructor, and a Book record whose Title parameter has a Description attribute without a target and whose Pages parameter has one that starts with property:

Program.cs
using System.ComponentModel;
using System.Reflection;

// Read the Description attribute of each property of Book.
foreach (PropertyInfo property in typeof(Book).GetProperties())
{
DescriptionAttribute? attribute = property.GetCustomAttribute<DescriptionAttribute>();
Console.WriteLine($"Property {property.Name}: {attribute?.Description ?? "(none)"}");
}

// Read the Description attribute of each parameter of Book's constructor.
ConstructorInfo constructor = typeof(Book).GetConstructors()[0];
foreach (ParameterInfo parameter in constructor.GetParameters())
{
DescriptionAttribute? attribute = parameter.GetCustomAttribute<DescriptionAttribute>();
Console.WriteLine($"Parameter {parameter.Name}: {attribute?.Description ?? "(none)"}");
}

// Title's attribute has no target, so it goes on the constructor parameter.
// Pages's attribute starts with property:, so it goes on the Pages property.
record Book(
[Description("The book's title")] string Title,
[property: Description("The number of pages")] int Pages);

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out property: when code reads the propertyThe attribute went on the parameter: Property Title: (none)Write [property: Description("...")]
Misspelling the target, as in properties:warning CS0658: 'properties' is not a recognized attribute location. Valid attribute locations for this declaration are 'field, property, param'. All attributes in this block will be ignored. The property had no descriptionUse one of the three targets that the warning lists
property: on a parameter of a class's primary constructorwarning CS0657: 'property' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'param'. All attributes in this block will be ignored. The reference: The compiler doesn't synthesize properties for primary constructor parameters on types that don't have the record modifier.Declare the property in the class and put the attribute on it, which gave Property Pages: The number of pages, or use a record
An attribute made only for properties, written without a targeterror CS0592: Attribute 'Label' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. The reference: the compiler doesn't use the AttributeUsage information to resolve ambiguous attribute targets.Add property:. Then it built, and the property had the attribute

FAQ​

Can one parameter have an attribute on the parameter and one on the property?​

Yes. Write both, one with param: and one with property:. In a check, the Pages property got The number of pages, and the parameter got Pages, as passed to the constructor.

What's the third target, field:, for?​

The property that a record generates stores its value in a field that you don't see. The reference: You can specify the field target value to apply an attribute to the backing field created for an automatically implemented property.

Conclusion​

On a positional record, an attribute goes on the constructor parameter unless you say otherwise. Write property: in front of it to put it on the property the record generates, which is where code that reads properties looks for it.

Additional Resources​