How to Add Comments to C# 9 Records
Asked Answered
T

1

10

C# 9 records have a short form like so:

public record Car(int CarId, int Cylinders, string Make, string Model);

How can I add documentation comments to the properties of the record? Note that this is different to this other question which asks about the long form.

Twoseater answered 20/11, 2020 at 17:37 Comment(0)
P
21

The correct way appears to be as simple as this:

/// <summary>
/// Represents a car.
/// </summary>
/// <param name="CarId">The id of the car.</param>
/// <param name="Cylinders">The number of cylinders.</param>
/// <param name="Make">The make of the car.</param>
/// <param name="Model">The model of the car.</param>
public record Car(int CarId, int Cylinders, string Make, string Model);

This does work in the IDE's IntelliSense (tests on VSCode) when you create a new instance of this record (ie new Car(...) will give you the information of the different parameters).

There appears however to be a problem in the compiler's warning system itself if you have <GenerateDocumentationFile>true</GenerateDocumentationFile> enabled in your .csproj. For every parameter you will get the following warning pair:

warning CS1572: XML comment has a param tag for 'CarId', but there is no parameter by that name
warning CS1573: Parameter 'CarId' has no matching param tag in the XML comment for 'Car.Car(int, int, string, string)' (but other parameters do)

So it does indeed work, but the compiler both moans about the parameter being not documented and having a documentation for a parameter that does not exist.

Put record parameters in scope of xml docs #49134 might fix the issue in the next version, hopefully.

Propagable answered 22/11, 2020 at 15:21 Comment(2)
FYI for others, the error was resolved in .NET 5.0.200 SDK, released March 02, 2021Anthe
Intellisense (starting to type 'param') and auto-filling in of all params upon adding 3 slashes above the record (as you can above a class) still doesn't work with updated VS2019 as of 9/2021Selfmade

© 2022 - 2024 — McMap. All rights reserved.