C# Comments

Comments are notes that you write inside C# source code for humans to read. The compiler ignores normal comments, so they do not change what the program does, but they can make code easier to understand, maintain, and document.

Good comments explain intent, assumptions, and warnings that are not obvious from the code itself. Poor comments repeat the code or become outdated, which can make a program harder to trust.

Overview: How Comments Work

C# has three main comment forms: single-line comments, multi-line comments, and XML documentation comments. A single-line comment begins with // and continues until the end of that physical line. A multi-line comment begins with /* and ends with */, and it can span part of a line, a full line, or many lines. XML documentation comments begin with /// and are normally placed before types and members such as classes, methods, properties, and fields.

During compilation, the lexer reads the source file and groups characters into tokens such as identifiers, keywords, literals, operators, and punctuation. Normal comments are recognized and discarded as trivia around those tokens. That means the compiler does not emit Intermediate Language for a normal comment, no object is allocated because of it, and the CLR never executes it. From the runtime’s point of view, a comment does not exist.

XML documentation comments are slightly different. They also do not become executable code, but the compiler can read them and produce a separate XML documentation file when the project enables documentation output. Tools such as IDE IntelliSense, API documentation generators, and package documentation sites can then display those comments to other developers.

Comments are useful because code often says what happens more clearly than why it happens. For example, a condition such as if (retryCount < 3) tells you the rule, but a comment might explain that the service rate-limits after repeated failures. The best comments capture business rules, external constraints, surprising decisions, and temporary workarounds.

Syntax

// A single-line comment

/* A multi-line comment
   can continue for several lines. */

/// <summary>
/// XML documentation comment for a type or member.
/// </summary>
Syntax Name Common use
// Single-line comment Short notes beside or above code
/* ... */ Multi-line comment Longer notes, temporary block comments, or inline explanation
/// XML documentation comment Public APIs, methods, classes, properties, and parameters
  • // comments end automatically at the next line break.
  • /* ... */ comments must be closed. Forgetting the closing marker comments out the rest of the file until the compiler finds one.
  • /// comments use XML-like tags such as <summary>, <param>, and <returns>.

Examples

Example 1: Single-line comments explain intent

using System;

class Program
{
    static void Main()
    {
        decimal price = 19.99m;
        decimal taxRate = 0.0825m; // Local sales tax rate: 8.25%

        decimal total = price + (price * taxRate);

        Console.WriteLine($"Total: ${total:0.00}");
    }
}

Output:

Total: $21.64

The comment does not repeat that taxRate is a tax rate; the variable name already says that. Instead, it records the specific local rule represented by the number. The compiler ignores the comment and compiles the arithmetic exactly as if the comment were not present.

Example 2: Multi-line comments for longer context

using System;

class Program
{
    static void Main()
    {
        int orderCount = 120;

        /*
           Shipping is free only after the warehouse confirms the order.
           This sample uses a simplified rule for demonstration.
        */
        bool qualifiesForFreeShipping = orderCount >= 100;

        Console.WriteLine($"Free shipping: {qualifiesForFreeShipping}");
    }
}

Output:

Free shipping: True

A multi-line comment is useful when one line would be cramped. Notice that the comment describes the larger business rule, while the code shows the simplified expression used in this program.

Example 3: XML documentation comments describe an API

using System;

class Program
{
    /// <summary>
    /// Converts a score from 0 through 100 into a pass/fail label.
    /// </summary>
    /// <param name="score">The numeric test score.</param>
    /// <returns>"Pass" when the score is at least 60; otherwise "Fail".</returns>
    static string GetResult(int score)
    {
        return score >= 60 ? "Pass" : "Fail";
    }

    static void Main()
    {
        Console.WriteLine(GetResult(72));
        Console.WriteLine(GetResult(41));
    }
}

Output:

Pass
Fail

XML documentation comments are structured so tools can understand them. In an IDE, hovering over GetResult can show the summary, parameter description, and return value. These comments are most valuable on code that other developers call.

How Comments Work Step by Step

  1. The compiler reads the source file as text.
  2. The lexer recognizes comment markers such as //, /*, and ///.
  3. Normal comments are skipped while the compiler builds tokens for real C# syntax.
  4. The parser builds a syntax tree from tokens such as class, static, string, and return.
  5. The compiler checks types, emits IL, and records metadata. Normal comments do not appear in the IL.
  6. If documentation output is enabled, XML documentation comments are processed into a separate XML file.

This explains why comments cannot fix invalid syntax. If a semicolon, brace, or quote is missing in real code, the compiler still reports an error. It also explains why comments have no performance cost at runtime: they do not become instructions.

Common Mistakes

Mistake 1: Forgetting to close a multi-line comment

using System;

class Program
{
    static void Main()
    {
        /* This comment never ends
        Console.WriteLine("Hello");
    }
}

This does not compile because the /* comment is never closed with */. The compiler keeps treating following text as part of the comment until it reaches the end of the file.

using System;

class Program
{
    static void Main()
    {
        /* This comment is closed correctly. */
        Console.WriteLine("Hello");
    }
}

Output:

Hello

Mistake 2: Using comments to hide unclear names

using System;

class Program
{
    static void Main()
    {
        int d = 14; // number of days before an invoice is overdue
        Console.WriteLine(d);
    }
}

This compiles, but the comment is doing work that the identifier should do. Clear names reduce the need for explanatory comments.

using System;

class Program
{
    static void Main()
    {
        int daysBeforeInvoiceIsOverdue = 14;
        Console.WriteLine(daysBeforeInvoiceIsOverdue);
    }
}

Output:

14

Mistake 3: Letting comments disagree with code

using System;

class Program
{
    static void Main()
    {
        // Add a 10% discount.
        decimal discountRate = 0.15m;
        Console.WriteLine($"Discount: {discountRate * 100:0}%");
    }
}

Output:

Discount: 15%

The program is valid, but the comment is wrong. Incorrect comments are worse than missing comments because they lead readers away from the truth. Update the comment, remove it, or express the rule with a clearer constant name.

Best Practices

  • Use comments to explain why code exists, not just what each statement does.
  • Prefer clear names and small methods before adding comments.
  • Keep comments close to the code they describe.
  • Update comments when the behavior changes.
  • Use XML documentation comments for public or reusable methods, especially when parameters have constraints.
  • Avoid large blocks of commented-out old code. Version control is a better place for history.
  • Do not write insulting, vague, or emotional comments. Future readers need facts.
  • When a comment explains a surprising workaround, include the reason and the condition for removing it.

Practice Exercises

  1. Write a program that calculates the final price of an item after tax. Add one useful comment that explains where the tax rate comes from.
  2. Create a method named IsAdult that returns true for ages 18 and above. Add XML documentation comments with <summary>, <param>, and <returns>.
  3. Find a comment that simply repeats a line of code, then improve the variable or method name so the comment can be removed.

Summary

  • C# comments are for humans; normal comments are ignored by the compiler and do not run.
  • // creates a single-line comment, while /* ... */ creates a multi-line comment.
  • /// creates XML documentation comments that tools can use for API help.
  • Comments should explain intent, constraints, decisions, and non-obvious behavior.
  • Bad comments can mislead readers, so keep them accurate and avoid using them to cover unclear code.