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.
using System;
// Print a greeting
Console.WriteLine("Hello"); // this runs
// Console.WriteLine("Bye"); // this line is disabledHello
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.
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*/, leavingc */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.
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 iadds nothing;// skip the header rowdoes. - Keep comments up to date — a wrong comment is worse than none.
- Prefer clear names over comments:
daysUntilExpiryneeds no explanation,ddoes. - Use
// TODO:to mark unfinished work; most editors list these for you.
Test yourself
Which syntax starts a single-line comment in C#?
- #
- --
- //
- <!--
What are /// comments used for?
- Disabling code faster
- XML documentation that tools can read
- Compiler directives
- Nothing — they are invalid