Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 182 ยท Getting Started

Comments and XML Documentation

Learn C# comments - single-line, multi-line and /// XML documentation comments, common doc tags, #region, #pragma, #nullable directives and good commenting habits.

Code is read far more often than it is written, including by you six months from now. Comments are text that the compiler ignores, there to explain things the code cannot say by itself: why a decision was made, what a tricky formula means, which bug a workaround avoids. A good comment saves an hour; a bad one lies, because nobody updated it after the code changed.

C# has three kinds of comment syntax, plus a special form, XML documentation comments, that tools turn into IntelliSense tooltips and generated documentation. It also has a few compiler directives (#region, #pragma, #nullable) that look a bit like comments but actually talk to the compiler. This lesson covers all of them and the habits professionals follow.

Single-line and multi-line comments

A single-line comment starts with // and runs to the end of the line. A multi-line comment starts with /* and ends with */.

C# The two comment styles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The output is 60 and Done. The last WriteLine before Done is disabled because it begins with //. Commenting code out like this is a handy trick while experimenting, but do not commit large blocks of dead code: version control remembers old code for you.

One difference matters: multi-line comments do not nest. The first */ closes the comment, so wrapping code that already contains a /* ... */ comment in another one breaks:

C#
/* outer begins
   /* inner comment */
   this line is now real code and causes a compile error
*/

Most developers therefore use // for almost everything and keep /* */ for the rare in-line comment. Editors comment out a selection with one shortcut (Ctrl+K, Ctrl+C in Visual Studio; Ctrl+/ in VS Code and Rider), putting // in front of every line.

Writing comments that help

Beginners often comment what the code does. Experienced developers comment why.

C#
// Bad: repeats the code
i++;   // add one to i

// Better: explains the intent that the code cannot
retryCount++;   // the server drops the first connection after a deploy, so we retry once

Guidelines that hold up over years:

  • Prefer clearer code to a comment. If you feel the need to explain int d = 86400;, name it instead: const int SecondsPerDay = 86400;.
  • Explain why, constraints, units, links to the bug or specification: // Max 255: the legacy API rejects longer names.
  • Keep comments true. When you change the code, change the comment, or delete it.
  • Do not use comments as a changelog or a signature. Source control tells who changed what and when.
  • Mark unfinished work with a tag: // TODO: handle empty input. IDEs list these tags and many teams have a rule that a TODO carries a ticket number.

If a comment explains a block of code, ask whether that block should be a method with a good name instead. ApplyDiscountForLoyalCustomers() needs no comment.

XML documentation comments

A comment that starts with three slashes, ///, and sits directly above a type or member is an XML documentation comment. Its content is XML, and tools read it: your editor shows it in tooltips when someone calls the method, and the compiler can collect all of it into an XML file (<GenerateDocumentationFile>true</GenerateDocumentationFile>) that documentation generators and NuGet use.

C# A documented method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The output is 5 and an empty line (printing null for a nullable value gives an empty string). The doc comments do nothing at run time; their value shows up in your editor. Hover over Hypotenuse in Visual Studio, VS Code or Rider and the summary, parameter descriptions and return value appear.

The common tags

Tag Purpose
<summary> One or two sentences: what the member is or does. The most important tag
<param name="x"> Describes parameter x
<typeparam name="T"> Describes a generic type parameter
<returns> What the method returns
<exception cref="ArgumentNullException"> A documented exception and when it happens
<remarks> Longer notes, design rationale
<example> with <code> A usage example
<see cref="Type.Member"/> A link to another type or member (checked by the compiler)
<paramref name="x"/> A reference to a parameter inside prose
<inheritdoc/> Copy the documentation from the base class or interface
<see langword="null"/> Formats a keyword such as null, true

cref attributes are validated: if you rename the method, the compiler warns about the broken reference, which keeps documentation from silently rotting.

When you type /// above a member in a good editor, it fills in the skeleton for you, including one <param> for every parameter.

Documenting exceptions and generics

C#
/// <summary>Returns the first element that satisfies a condition.</summary>
/// <typeparam name="T">The element type.</typeparam>
/// <param name="items">The sequence to search.</param>
/// <param name="test">The condition.</param>
/// <returns>The first match.</returns>
/// <exception cref="ArgumentNullException"><paramref name="items"/> or <paramref name="test"/> is <see langword="null"/>.</exception>
/// <exception cref="InvalidOperationException">No element satisfies <paramref name="test"/>.</exception>
public static T First<T>(IEnumerable<T> items, Func<T, bool> test)
{
    ArgumentNullException.ThrowIfNull(items);
    ArgumentNullException.ThrowIfNull(test);
    foreach (T item in items)
    {
        if (test(item))
        {
            return item;
        }
    }
    throw new InvalidOperationException("No element matches.");
}

(You will learn generics and exceptions later. For now notice how the doc comment lists what can go wrong, which is the information callers need most.)

What to document

Document every public type and member of a library: public APIs are a contract. Inside an application, document what is not obvious and skip the rest. A comment like /// <summary>Gets the name.</summary> on a property called Name adds noise, not information. Short, accurate and useful beats long and mechanical.

There is also a compiler switch: with documentation generation on, warning CS1591 reports public members that lack a doc comment. Libraries turn this on (sometimes as an error) to force complete documentation.

Directives: #region, #pragma, #nullable

Lines starting with # are preprocessor directives. They are instructions to the compiler, not comments, and they must be on a line by themselves. These three show up often.

#region and #endregion

A region marks a foldable block in the editor. It has no effect on the program.

C# Regions fold code in the editor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Regions can hide too much. Many teams discourage them because a class that needs five regions probably needs splitting into five classes, and a hidden region may hide a bad method.

#nullable

Nullable reference types (covered in Nullable Reference Types) are switched on for the whole project, but you can change the setting for a stretch of code. This is mainly useful when migrating old code.

C#
#nullable disable
string legacy = null;      // no warning in this region
#nullable restore          // go back to the project's setting

#pragma warning

#pragma warning disable silences a specific compiler warning for the code below it, and restore turns it back on. Always name the exact warning and keep the region tiny.

C# Disabling one warning on purpose

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Remove the two #pragma lines and the verifier would show warning CS0219: The variable 'unused' is assigned but its value is never used. Suppress warnings only when you are sure the compiler is wrong or the situation is deliberate, and explain why in a comment.

#if, #define: conditional compilation

#if includes code only when a symbol is defined. Projects define DEBUG in Debug builds, and RELEASE is conventional in Release builds. You can also define your own symbols at the top of a file.

C# Conditional compilation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Only VERBOSE is defined here, so you see just the first line; our editor does not define DEBUG, but a Debug build from the dotnet CLI does. #define must come before any other code in the file. In a real project, SDK-defined symbols such as NET10_0_OR_GREATER are useful for libraries that compile against several .NET versions (our single-file editor does not define them, so that is read-only knowledge). For simple on/off behaviour at run time prefer a configuration setting, as conditional compilation makes testing harder.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line is an XML documentation comment?

    Documentation comments begin with three slashes and contain XML tags such as <summary>. Tools use them for tooltips and generated docs.
  2. 2. Why do multi-line comments (/* ... */) cause trouble when you try to nest them?

    Block comments do not nest. The first closing marker ends the comment, whichever opening marker it matches.
  3. 3. What is a good guideline for the content of a comment?

    Code already shows what happens. Comments earn their keep by capturing intent, constraints and reasons. Source control records who and when.
  4. 4. What does #region Setup do?

    Regions are purely an editor convenience. Variables declared inside are still in the enclosing scope.
  5. 5. What is the safest way to use #pragma warning disable?

    Name the exact warning (for example CS0219), keep the region tiny, restore it afterwards and say why in a comment.

Summary

  • // comments to the end of the line; /* */ spans lines but does not nest.
  • Good comments explain why; if you need to explain what, improve names or extract a method.
  • /// XML documentation comments feed tooltips and generated docs; the key tags are summary, param, returns, exception, remarks, example, see cref.
  • cref links are checked by the compiler; <inheritdoc/> reuses docs from a base member.
  • #region folds code in the editor, #nullable changes nullable annotations locally, and #pragma warning silences a named warning for a small range.
  • #if / #define include code at compile time; use configuration for run-time behaviour instead.

Next: Console Output and Formatting covers Console.Write, interpolation and format specifiers.