user2136963
user2136963

Reputation: 2606

Can I reference property comments in constructor comments?

If my class has a commented public property, which is assigned via constructor, can I reference its description from a description of constructor argument with the same name?

public class MyClass
{
    /// <summary>
    /// x description
    /// </summary>
    public int x { get; private set; }
    /// <summary>
    /// y description
    /// </summary>
    public int y { get; private set; }
    /// <summary>
    /// Constructor description
    /// </summary>
    /// <param name="x">How do I reference x description from here?</param>
    /// <param name="y">And y description?</param>
    public MyClass(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

Upvotes: 14

Views: 6809

Answers (2)

Luke
Luke

Reputation: 1039

This is possible using <inheritdoc/>, specifically by making use of the optional cref and path attributes.

Note: I'm unsure what language or framework version this became available, it works for me using .NET 5 / C# 9. If someone comments with a starting version I can edit.

Reference: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/recommended-tags#inheritdoc

For your example (the difference is within the param elements on the constructor XML comments):

public class MyClass
{
    /// <summary>
    /// x description
    /// </summary>
    public int x { get; private set; }
    /// <summary>
    /// y description
    /// </summary>
    public int y { get; private set; }
    /// <summary>
    /// Constructor description
    /// </summary>
    /// <param name="x"><inheritdoc cref="x" path='/summary'/></param>
    /// <param name="y"><inheritdoc cref="y" path='/summary'/></param>
    public MyClass(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

This will make the constructor parameters inherit the summary comments from your parameters, reducing redundancy.

Upvotes: 5

Jon Skeet
Jon Skeet

Reputation: 1500065

You can't include the description, but you can link to the property documentation with the <see> tag. For example:

<param name="x">The initial value for <see cref="x"/></param>

As an aside, I would strongly urge you to follow .NET naming conventions, where public members start with capital letters.

Upvotes: 22

Related Questions