What is the right way to add comments with C# 9 record with Nullable enabled?
If I try
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 warning.
Non-nullable property 'FirstName' must contain a non-null value when exiting constructor. Consider declaring the property as nullable.
If I try
public record Person(string firstName, string lastName);
I get 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
Single-line comments start with two forward slashes ( // ). Any text between // and the end of the line is ignored by the compiler (will not be executed).
In computer programming, a comment is a programmer-readable explanation or annotation in the source code of a computer program. Comments are statements that are not executed by the compiler and interpreter.
A C++ comment is written in one of the following ways: The /* (slash, asterisk) characters, followed by any sequence of characters (including new lines), followed by the */ characters. This syntax is the same as ANSI C. The // (two slashes) characters, followed by any sequence of characters.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With