C# Comments - Documentation Guide
Introduction to Comments in C#
Comments in C# are ignored by the compiler but are used by developers to describe, explain, or annotate code. They improve code readability and make future maintenance easier.
C# supports three main types of comments: single-line comments, multi-line comments, and XML documentation comments. Each is useful in different contexts, from quick notes to generating structured documentation.
Types of Comments
C# provides different types of comments depending on the documentation need:
Example
using System;
namespace CommentTypes
{
class Program
{
static void Main(string[] args)
{
// Single-line comment
// Describes code briefly on one line
/*
* Multi-line comment
* Can span several lines
* Useful for longer explanations
*/
Console.WriteLine("Hello, World!"); // Comment after code
// Disable code temporarily
// Console.WriteLine("This won't run");
}
}
/// <summary>
/// XML documentation comment for generating API docs
/// </summary>
public class DocumentedClass
{
/// <summary>
/// Gets or sets the name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Prints a greeting message
/// </summary>
/// <param name="name">The name to greet</param>
public void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
}
}
Output
Hello, World!
Best Practices for Comments
Good comments explain why code exists rather than restating what is already obvious. They should clarify intent, document complex logic, and highlight areas that need work (using TODO or FIXME). Avoid redundant or misleading comments.
Example
using System;
namespace CommentBestPractices
{
class Program
{
static void Main(string[] args)
{
// Good: Explain why the code is here
// Calculate area of circle
double radius = 5.0;
double area = Math.PI * radius * radius; // Formula is self-explanatory
// Bad: Redundant
// Set x to 10
int x = 10;
// Good: Document non-trivial algorithm
// Using Euclidean algorithm to compute GCD
int a = 56, b = 98;
while (b != 0)
{
int temp = b;
b = a % b;
a = temp;
}
Console.WriteLine("GCD: " + a);
// TODO: Add error handling
// FIXME: Might be off by one in certain edge cases
}
}
}
Output
GCD: 14