TExcelTAD
Home › C# › C# Comments

C# Comments

Comments are notes for humans. The compiler ignores them completely, so they never change what a program does. Use them to explain why code exists, to leave reminders, or to temporarily switch off a line while experimenting.

Single-line comments

Two slashes // start a comment that runs to the end of the line. It can sit on its own line or after a statement.

csharp · try it yourself
using System;

// Print a greeting
Console.WriteLine("Hello");   // this runs
// Console.WriteLine("Bye");  // this line is disabled
Hello

Multi-line comments

Text between /* and */ is a comment, even if it spans several lines. It can also be placed in the middle of a line.

csharp · try it yourself
using System;

/*
  This program calculates the area
  of a rectangle.
*/
int width = 4;
int height = 3;
Console.WriteLine(width * /* times */ height);
12

Note: Multi-line comments cannot be nested. In /* a /* b */ c */ the comment ends at the first */, leaving c */ as broken code.

XML documentation comments

C# has a third kind of comment: three slashes /// followed by XML tags. These documentation comments are read by tools — your editor shows them as tooltips, and the compiler can export them into an XML file used to build API documentation.

csharp · try it yourself
using System;

class Program
{
    /// <summary>
    /// Converts a temperature from Celsius to Fahrenheit.
    /// </summary>
    /// <param name="celsius">Temperature in degrees Celsius.</param>
    /// <returns>The temperature in degrees Fahrenheit.</returns>
    static double ToFahrenheit(double celsius)
    {
        return celsius * 9 / 5 + 32;
    }

    static void Main()
    {
        Console.WriteLine(ToFahrenheit(100));
        Console.WriteLine(ToFahrenheit(-40));
    }
}
212
-40

Common documentation tags:

Tag Purpose
<summary> Short description of the member
<param name="x"> Describes one parameter
<returns> Describes the return value
<exception cref="T"> Documents an exception the method may throw
<example> / <code> Usage examples

Writing good comments

  • Explain why, not what. i++; // add one to i adds nothing; // skip the header row does.
  • Keep comments up to date — a wrong comment is worse than none.
  • Prefer clear names over comments: daysUntilExpiry needs no explanation, d does.
  • Use // TODO: to mark unfinished work; most editors list these for you.

Test yourself

Which syntax starts a single-line comment in C#?

  1. #
  2. --
  3. //
  4. <!--

What are /// comments used for?

  1. Disabling code faster
  2. XML documentation that tools can read
  3. Compiler directives
  4. Nothing — they are invalid