Comments allow us to include notes and explanations within the code. These notes help make the code easier to understand for other programmers, as well as for ourselves when reviewing the project in the future.
Additionally, comments allow temporarily disabling code snippets without deleting them, which is useful for testing and debugging (but only for testing, leaving it there is a mess 😊).
In C#, there are several types of comments that allow annotating the code in different ways:
Single-line comments: For brief notes and specific clarifications.
Multi-line comments: For more extensive explanations that span several lines.
XML comments: Used to document the code and generate automatic documentation.
If you want to learn about Comments in programming
check out the Introduction to Programming Course read more
Single-line comments
Single-line comments in C# start with two forward slashes (//
). Any text that appears after //
on the same line is considered a comment and is ignored by the compiler.
These comments are appropriate for brief annotations or temporarily disabling a line of code:
// This is a single-line comment
int result = 5 + 3; // Sum of two numbers
This type of comment is useful for briefly describing what a specific line of code does without interrupting its readability.
Multi-line comments
When more extensive comments are needed, multi-line comments are a suitable option. These comments start with /*
and end with */
.
Everything between these two symbols will be treated as a comment and will not be executed.
/* This is a multi-line comment.
It can span several lines and is useful
when explaining the purpose of
a block of code or including a detailed description. */
int result = 5 * 10;
Multi-line comments are useful when you need to write a detailed explanation or when you want to disable an entire block of code during the debugging process.
XML comments
C# also allows creating XML comments, which are especially useful for documenting methods, classes, and properties.
XML comments start with three forward slashes (///
) and can contain tags like <summary>
, <param>
, and <returns>
. Here’s an example:
/// <summary>
/// Calculates the sum of two integers.
/// </summary>
/// <param name="a">The first number to sum.</param>
/// <param name="b">The second number to sum.</param>
/// <returns>The result of adding both numbers.</returns>
public int Add(int a, int b)
{
return a + b;
}
In this example:
<summary>
describes the purpose of the method.<param>
describes the input parameters.<returns>
describes the return value.
XML comments are used to create detailed documentation that can be exported and used by other developers, helping to understand the functionality of each method or class.