Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Add Comments to C# 9 Records

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.

like image 985
Muhammad Rehan Saeed Avatar asked Nov 20 '20 17:11

Muhammad Rehan Saeed


People also ask

What is the use of /* in C?

The text inside the /* and */ tags will be considered as comments and will not be executed or compiled. This is to provide the coder with a clear knowledge of the code and its application or use. The output is printed to the console screen using this C command. This function is being used to wait for the user's input.

How do you comment out a block of code in C?

You can comment out selected block of code with C style comment /* */ . To do so, select the block of code you want to comment out and press CTRL+Shift+/ (slash).

How do you comment in programming?

Summary of comment types:use // for a single line. Everything from the // to the end of that line of the file is ignored by the program and is only for use by the human reader of the code.


1 Answers

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.

like image 159
Simon Mattes Avatar answered Oct 19 '22 01:10

Simon Mattes