'Add comments to records - C# 9

I'm looking for a way to add comments on record properties, in C# 9

When I try this code :

public record Person
{
    /// <summary>
    /// Gets the first name.
    /// </summary>
    public string FirstName { get; init; }
    
    /// <summary>
    ///  Gets the last name.
    /// </summary>
    public string LastName { get; init; }
}

I get this warning :

Non-nullable property 'FirstName' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.

When I try :

public record Person(string firstName, string lastName);

I get this warning:

Missing XML comment for publicly visible type or member 'Person.firstName'


This does not work either.

/// <summary>
/// Person.
/// </summary>
/// <param name="FirstName">Get the first name.</param>
/// <param name="LastName">Get the last name.</param>
public record Person(string FirstName, string LastName);

Gives warning:

XML comment has a param tag for 'FirstName', but there is no parameter by that name



Solution 1:[1]

For the first case, the warning you're getting is unrelated to documentation comments. You have a non-nullable property with default value equals to null. That's why you get warning.

For the second case, this is a known issue in the compiler that's being fixed in dotnet/roslyn#49134.

Edit based on @matt-johnson-pint comment, this was fixed with Visual Studio 16.9 and .NET 5.0.200 SDK

Solution 2:[2]

You can write it like this:

public record Person(string FirstName, string LastName)
{
    /// <summary>
    /// Gets the first name.
    /// </summary>
    public string FirstName { get; init; } = FirstName;

    /// <summary>
    ///  Gets the last name.
    /// </summary>
    public string LastName { get; init; } = LastName;
}

This way the record is created with (string,string)-constructor and deconstructor like in the case of this notation:

public record Person(string firstName, string lastName);

But you also have the properties to put the comments on.

BTW As I understand it, this is legit, as long as the properties and arguments have the same name and the same type, the compiler knows what to do. You can also use this, if the properties should have a different interface, like a set instead of a init or only a get and so on.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Martini Bianco