0
0
CsharpHow-ToBeginner · 3 min read

How to Comment in C#: Syntax and Examples

In C#, you can add comments using // for single-line comments and /* */ for multi-line comments. For documentation, use /// to create XML comments that help explain your code.
📐

Syntax

There are three main ways to write comments in C#:

  • Single-line comment: Starts with // and continues to the end of the line.
  • Multi-line comment: Starts with /* and ends with */, can span multiple lines.
  • XML documentation comment: Starts with /// and is used to generate documentation.
csharp
// This is a single-line comment

/*
 This is a multi-line comment
 It can span multiple lines
*/

/// <summary>
/// This is an XML documentation comment
/// </summary>
💻

Example

This example shows how to use single-line, multi-line, and XML documentation comments in a simple C# program.

csharp
using System;

namespace CommentExample
{
    /// <summary>
    /// This class demonstrates comments in C#.
    /// </summary>
    class Program
    {
        static void Main()
        {
            // This is a single-line comment
            Console.WriteLine("Hello, world!");

            /* This is a multi-line comment
               It can explain multiple lines of code
               or temporarily disable code. */

            Console.WriteLine("Comments help explain code.");
        }
    }
}
Output
Hello, world! Comments help explain code.
⚠️

Common Pitfalls

Common mistakes when commenting in C# include:

  • Forgetting to close multi-line comments, which causes errors.
  • Using // for multi-line comments, which only comments one line at a time.
  • Misusing XML comments outside of methods or classes, which can cause warnings.
csharp
// Wrong: multi-line comment not closed
/* This comment is not closed */

// Right: properly closed multi-line comment
/* This comment is properly closed */
📊

Quick Reference

Comment TypeSyntaxUse Case
Single-line comment// comment textBrief notes or disable one line
Multi-line comment/* comment text */Explain multiple lines or disable blocks
XML documentation/// commentGenerate code documentation

Key Takeaways

Use // for quick single-line comments in C#.
Use /* */ to comment out multiple lines or blocks of code.
Use /// to write XML documentation comments for methods and classes.
Always close multi-line comments to avoid syntax errors.
Comments improve code readability and maintainability.