Skip to content

Comments and Documentation

Rule prefix: DOC · Baseline: C# 14 / .NET 10 · Levels: DO · DO NOT · CONSIDER · AVOID

Home · Rule index · Naming cheat sheet

This chapter covers two kinds of comment. Line comments (//) explain why code does something and sit in the body of a member; XML documentation comments (///) describe the public contract of a type or member and feed IntelliSense and API documentation. The first group of rules says how to write a line comment, what it may say and what must never be committed in a comment. The second group says what to document, how to avoid copying documentation, and which compiler settings keep the documentation consistent. Layout of comment lines (line length, blank lines) follows page 01; the exceptions a member throws are designed on page 10.

The compiler checks XML documentation only when the project generates the documentation file (DOC-023). Even then it checks consistency (a CS warning for a wrong cref or param), not content, so rules about what a comment says are checked in review. They are Manual rules and appear in the "Manual review only" table on page 15.

Rule index

ID Level Rule Enforced
DOC-010 DO write comments with // followed by one space, on their own line above the code they explain, as sentences that start with a capital letter and end with a period, and do not use /* */ comments. Manual
DOC-011 DO write a comment only to explain why the code does something (a business rule, a workaround, a non-obvious constraint), never to restate what the code does. Manual
DOC-012 DO NOT leave commented-out code in a file; delete it and rely on version control to recover it. Manual
DOC-013 DO NOT commit a TODO, HACK, FIXME or similar marker comment; open an issue for the remaining work and reference it in the pull request instead. Manual
DOC-014 DO NOT add a banner comment with copyright, author, creation date or change history at the top of a source file; version control and the repository licence file carry that information. Manual
DOC-020 DO document every public and protected type and member of a library with <summary>, and add <param> for each parameter, <returns> for non-void results and <exception> for each exception the member throws on purpose. Manual
DOC-021 DO document an override or interface implementation with /// <inheritdoc/> instead of copying the base documentation, and add text only for behaviour that differs. Manual
DOC-022 DO keep XML documentation consistent with the code: every <param> names an existing parameter, every parameter of a documented member has a <param>, and every cref resolves. CS1572, CS1573, CS1574
DOC-023 DO set GenerateDocumentationFile to true in every project, keep CS1591 at none for applications and tests, and set CS1591 to warning in projects that ship a public library. CS1591

Comments

These rules cover the form and content of line comments and what must not be committed in a comment.

DOC-010

DO write comments with // followed by one space, on their own line above the code they explain, as sentences that start with a capital letter and end with a period, and do not use /* */ comments.

✅ Correct

private const decimal FreeShippingThreshold = 50m;
private const decimal StandardShippingFee = 4.95m;

public static decimal CalculateShippingFee(Order order)
{
    // Free shipping is a promotion, not a carrier rate.
    if (order.Total >= FreeShippingThreshold)
    {
        return 0m;
    }

    return StandardShippingFee;
}

❌ Incorrect — comments without the space, the capital letter or the period, an end-of-line comment and a block comment

var order = new Order(7, TimeProvider.System.GetUtcNow());
//Free shipping is a promotion. // No space after the slashes.
// free shipping is a promotion. // No capital letter at the start.
// Free shipping is a promotion // No period at the end.
bool shipsFree = order.Total > 0m; // Free shipping is a promotion. // Explanation at the end of a code line.
/* Free shipping is a promotion. */ // Block comment.

Why: A comment above the code reads in the order the code is read, and an end-of-line comment pushes the line toward the limit in FMT-040. A /* */ comment cannot contain another /* */ comment, so it breaks when a block of code that already holds one is commented out. The capital letter, the final period and the single space after // are the details the Microsoft conventions ask for, and one form makes every comment look the same in a review.

Exceptions:

  • XML documentation comments (///) follow DOC-020, not this rule.

Scope: Line comments in code (XML documentation: DOC-020) · Enforced: Manual · Sources: MS-CONV, SA, AV

DOC-011

DO write a comment only to explain why the code does something (a business rule, a workaround, a non-obvious constraint), never to restate what the code does.

✅ Correct

private const decimal MaxParcelWeightKg = 30m;

// Carriers reject parcels heavier than 30 kg, so split the shipment.
public static int CountParcels(decimal weightKg) => (int)Math.Ceiling(weightKg / MaxParcelWeightKg);

❌ Incorrect — comments that repeat the code

var order = new Order(7, TimeProvider.System.GetUtcNow());
int count = 0;
// Loop over the lines. // Restates the code.
foreach (OrderLine line in order.Lines)
{
    // Increment count. // Restates the code.
    count++;
}

Why: The code already says what it does, and a comment that repeats it has to be edited with the code or it becomes wrong. The reason (the carrier limit, the promotion, the workaround for a defect) is the one thing the code cannot show, and the next maintainer would otherwise remove or break the line that encodes it.

Exceptions:

  • XML documentation describes what a member does; it follows DOC-020. This rule covers // comments only.

Scope: Comments in code · Enforced: Manual · Sources: AV, MS-CONV

DOC-012

DO NOT leave commented-out code in a file; delete it and rely on version control to recover it.

✅ Correct

public static decimal CalculateNetTotal(Order order, decimal discount) => order.Total - discount;

❌ Incorrect — a line of code left in a comment

public static decimal CalculateNetTotal(Order order, decimal discount)
{
    // decimal oldTotal = CalculateLegacyTotal(order); // Commented-out code.
    return order.Total - discount;
}

Why: Version control keeps every earlier version, so a commented-out line adds nothing the history does not hold. It also leaves the reader unsure whether the line was disabled on purpose and whether it still compiles, because the compiler does not check it.

Scope: Code that is no longer used · Enforced: Manual · Sources: AV

DOC-013

DO NOT commit a TODO, HACK, FIXME or similar marker comment; open an issue for the remaining work and reference it in the pull request instead.

✅ Correct

public static void Ship(Order order)
{
    if (order.Status is OrderStatus.Paid)
    {
        order.Ship();
    }
}

❌ Incorrect — marker comments that track work in the code

public static void Ship(Order order)
{
    // TODO: handle partial shipments. // Work tracked in a comment.
    if (order.Status is OrderStatus.Paid)
    {
        // HACK: retry the shipment twice. // Marker comment.
        order.Ship();
    }
}

Why: Nothing reports a marker comment, so it stays until someone happens to read it, while an issue has an owner, a status and a place in planning. The pull request that leaves work undone links the issue, so the gap is visible at review time. A // TODO(<issue>) comment still tracks the work in code.

Scope: Work-tracking comments · Enforced: Manual · Sources: AV

DOC-014

DO NOT add a banner comment with copyright, author, creation date or change history at the top of a source file; version control and the repository licence file carry that information.

✅ Correct

namespace Contoso.Orders;

public sealed class ShippingLabel
{
    public required string Text { get; init; }
}

❌ Incorrect — a banner with a copyright line and an author line

// Copyright (c) Contoso. All rights reserved. // File header banner.
// Author: Avery Example // Author line.

namespace Contoso.Orders;

public sealed class ShippingLabel
{
    public required string Text { get; init; }
}

Why: The author, the date and the change history are already in version control, where they stay correct; a banner copies them into every file and goes stale. The licence file states the copyright once for the repository. IDE0073 would check a header, but only when file_header_template is set, and the shipped configuration leaves it unset.

Scope: The top of every source file · Enforced: Manual · Sources: MS-IDE, SA

XML documentation

These rules cover what to document, how to avoid copying documentation and which compiler settings keep it consistent.

DOC-020

DO document every public and protected type and member of a library with <summary>, and add <param> for each parameter, <returns> for non-void results and <exception> for each exception the member throws on purpose.

✅ Correct

/// <summary>Creates an empty order.</summary>
/// <param name="customerId">The identifier of the customer who places the order.</param>
/// <param name="createdAt">The time at which the order is created.</param>
/// <returns>The new order with no lines.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="customerId"/> is not positive.</exception>
public static Order Create(int customerId, DateTimeOffset createdAt)
{
    ArgumentOutOfRangeException.ThrowIfNegativeOrZero(customerId);

    return new Order(customerId, createdAt);
}

❌ Incorrect — only a summary; the param, returns and exception tags are missing

/// <summary>Creates an empty order.</summary> // The param, returns and exception tags are missing.
public static Order Create(int customerId, DateTimeOffset createdAt)
{
    ArgumentOutOfRangeException.ThrowIfNegativeOrZero(customerId);

    return new Order(customerId, createdAt);
}

Why: The consumer of a library reads the contract in IntelliSense and in the generated documentation, and does not open the source. The summary says what the member does; the tags say what each argument means, what comes back and which failure to expect. A type is documented the same way, with a <summary>. The compiler reports only a public member with no XML comment at all (CS1591, which the shipped configuration sets to none, see DOC-023); a missing returns or exception tag is found in review.

Exceptions:

  • Application code (executables, services, test projects): documentation is recommended for members that other teams call, and CS1591 stays off there (DOC-023).
  • An override or interface implementation uses <inheritdoc/> (DOC-021).

Scope: Public and protected types and members of libraries (application code: recommended) · Enforced: Manual · Sources: MS-CONV, MS-XMLDOC, AV, SA

DOC-021

DO document an override or interface implementation with /// <inheritdoc/> instead of copying the base documentation, and add text only for behaviour that differs.

✅ Correct

using System.Globalization;

namespace Contoso.Orders;

/// <summary>Ranks orders by total.</summary>
public sealed record OrderRank(decimal Total) : IComparable<OrderRank>
{
    /// <inheritdoc/>
    public int CompareTo(OrderRank? other) => other is null ? 1 : Total.CompareTo(other.Total);

    /// <inheritdoc/>
    public override string ToString() => Total.ToString(CultureInfo.InvariantCulture);
}

❌ Incorrect — the interface summary copied onto the implementation

namespace Contoso.Orders;

/// <summary>Ranks orders by total.</summary>
public sealed record OrderRank(decimal Total) : IComparable<OrderRank>
{
    /// <summary>Compares this instance with another instance.</summary> // Copied from the interface.
    public int CompareTo(OrderRank? other) => other is null ? 1 : Total.CompareTo(other.Total);
}

Why: A copy of the base documentation drifts from the original when the base member changes, and the reader of the implementation sees two texts that may disagree. <inheritdoc/> shows the base text in IntelliSense and in the generated documentation and stays correct by construction.

Scope: Overrides and interface implementations · Enforced: Manual · Sources: MS-XMLDOC, MS-CONV

DOC-022

DO keep XML documentation consistent with the code: every <param> names an existing parameter, every parameter of a documented member has a <param>, and every cref resolves.

✅ Correct

namespace Contoso.Orders;

/// <summary>Calculates totals from <see cref="OrderLine"/> amounts.</summary>
public static class OrderTotalCalculator
{
    /// <summary>Adds the tax to a net amount.</summary>
    /// <param name="value">The net amount.</param>
    /// <param name="taxRate">The tax rate, for example 0.2 for 20 percent.</param>
    /// <returns>The gross amount.</returns>
    public static decimal AddTax(decimal value, decimal taxRate) => value + (value * taxRate);
}

❌ Incorrect — a cref that does not resolve and a param tag for a missing parameter

namespace Contoso.Orders;

/// <summary>Calculates totals; see <see cref="OrderServic"/>.</summary> // The cref does not resolve.
public static class OrderTotalCalculator
{
    /// <summary>Adds the tax to a net amount.</summary>
    /// <param name="amount">The net amount.</param> // The param tag names no parameter.
    public static decimal AddTax(decimal value, decimal taxRate) => value + (value * taxRate);
}

Why: A param tag or cref that points at nothing gives the reader a name that does not exist, and the generated documentation links to nowhere. The compiler reports CS1572 (a param tag without a parameter), CS1573 (a parameter without a tag when other parameters have one) and CS1574 (an unresolved cref), but only when the project generates the documentation file (DOC-023).

Scope: XML documentation comments · Enforced: CS1572, CS1573, CS1574 · Sources: MS-XMLDOC, MS-CS1591

DOC-023

DO set GenerateDocumentationFile to true in every project, keep CS1591 at none for applications and tests, and set CS1591 to warning in projects that ship a public library.

✅ Correct — Directory.Build.props

<Project>
  <PropertyGroup>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
  </PropertyGroup>
</Project>

✅ Correct — the shared .editorconfig (applications and tests)

[*.cs]
dotnet_diagnostic.CS1591.severity = none

✅ Correct — a .editorconfig inside the folder of a library

[*.cs]
dotnet_diagnostic.CS1591.severity = warning

❌ Incorrect — the documentation file is not generated, so IDE0005 stops running in the build

<Project>
  <PropertyGroup>
    <Nullable>enable</Nullable>
  </PropertyGroup>
</Project>

Why: IDE0005 (FMT-063) and the XML documentation checks (DOC-022) run in dotnet build only when the project generates the documentation file. That setting also raises CS1591 for every undocumented public member, which floods application code, so the shared configuration ships CS1591 at none and a library opts in with its own .editorconfig.

Scope: Every project; the CS1591 warning for libraries · Enforced: CS1591 · Sources: MS-CS1591, MS-IDE, MS-MSBUILD

  • FMT-040: the line-length limit, which applies to comment lines too.
  • FMT-063: unnecessary using directives, which the build reports only when DOC-023 is met.
  • TOOL-014: the Directory.Build.props settings, including GenerateDocumentationFile.
  • Page 10: which exceptions a member throws, and therefore which <exception> tags it needs.

Sources

AV · MS-CONV · MS-CS1591 · MS-IDE · MS-MSBUILD · MS-XMLDOC · SA


Previous: Types and Members · Home · Next: Exceptions and Error Handling