csharp-comentarios

Comments in C#

  • 3 min

Comments allow us to include notes and explanations within the code. These notes help make the code easier to understand both for other programmers and for ourselves when reviewing the project in the future.

Furthermore, comments allow temporarily disabling code fragments without deleting them, which is useful for testing and debugging (but only for testing, leaving it there is sloppy 😊).

In C#, there are several types of comments that allow annotating code in different ways:

  • Single-line comments: For brief notes and specific clarifications.
  • Multi-line comments: For more extensive explanations spanning several lines.
  • XML comments: Used to document code and generate automatic documentation.

If you want to learn more, check out the Introduction to Programming Course

Single-Line Comments

Single-line comments in C# start with two forward slashes (//). All text after // on the same line is considered a comment and is ignored by the compiler.

These comments are suitable for brief annotations or to temporarily disable a line of code:

// This is a single-line comment
int result = 5 + 3; // Sum of two numbers
Copied!

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 found between these two symbols will be treated as a comment and will not be executed.

/* This is a multi-line comment.
   It can span multiple lines and is useful
   when you need to explain the purpose of
   a block of code or include a detailed description. */
int result = 5 * 10;
Copied!

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 add.</param>
/// <param name="b">The second number to add.</param>
/// <returns>The result of adding both numbers.</returns>
public int Add(int a, int b)
{
    return a + b;
}
Copied!

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 them understand the functionality of each method or class.