Comments in C# are notes written inside source code for humans to read. The compiler ignores comments, so they do not directly affect program execution. Comments are used to explain intent, document important decisions, describe public APIs, temporarily disable code during debugging, and make complex logic easier to understand.
Good comments make code easier to maintain. Bad comments create noise, repeat obvious code, or become outdated and misleading. Learning how to write useful comments is part of learning how to write professional C# code.
What Are Comments in C#?
A comment is text placed inside the program source file that is ignored by the compiler. It helps developers understand the code, but it does not become part of the executable logic.
// This is a comment
Console.WriteLine("Hello C#");
The first line is for the programmer. The second line is actual executable code.
Comments should explain why something exists, not repeat what the code already says clearly.
Types of Comments in C#
| Comment Type | Syntax | Use |
|---|---|---|
| Single-line comment | // | Short notes on one line |
| Multi-line comment | /* */ | Longer comments across multiple lines |
| XML documentation comment | /// | Documentation for classes, methods, properties, and APIs |
Single-Line Comments in C#
A single-line comment starts with //. Everything after // on that line is ignored by the compiler.
// Print welcome message
Console.WriteLine("Welcome to C# programming");
Single-line comments are best for short explanations. They are common above a line or block of code when a small note is enough.
Inline Comments
A comment can also appear after code on the same line.
int maxAttempts = 3; // limit login retries
Inline comments should be used carefully. If they are too long, they make code harder to scan. If a variable name already explains the meaning, an inline comment may be unnecessary.
Multi-Line Comments in C#
A multi-line comment starts with /* and ends with */. It can span multiple lines.
/*
This program calculates the final bill
after applying discount and tax.
*/
Console.WriteLine("Bill calculated");
Multi-line comments are useful for longer notes, but they should not be used to write large essays inside code. Long explanations often belong in documentation, design notes, or README files.
XML Documentation Comments
C# supports XML documentation comments using triple slashes: ///. These comments are commonly used to document public classes, methods, properties, parameters, and return values.
/// <summary>
/// Adds two integers and returns the result.
/// </summary>
/// <param name="a">First number.</param>
/// <param name="b">Second number.</param>
/// <returns>The sum of both numbers.</returns>
int Add(int a, int b)
{
return a + b;
}
XML documentation comments can be used by IDEs to show tooltips and can also be exported into documentation files if the project is configured to generate XML documentation output.
Why Comments Are Used
- To explain complex logic.
- To document why a decision was made.
- To describe public APIs.
- To make code easier for other developers to understand.
- To leave short notes during debugging or refactoring.
- To warn about important assumptions or limitations.
Good Comment Example
// Retry only network timeouts because validation errors will not succeed later.
if (error.Type == ErrorType.Timeout)
{
RetryRequest();
}
This comment is useful because it explains the reason behind the retry rule. The code shows what happens, but the comment explains why it happens.
Bad Comment Example
// Increase count by one
count++;
This comment is weak because the code already says the same thing. Comments like this add noise without adding understanding.
Comments vs Clean Code
Comments should not be used as a replacement for clear code. If the code is confusing because names are bad or logic is too tangled, improving the code is usually better than adding many comments.
// Bad: unclear name needs explanation
int d = 7; // number of days before account expires
// Better: name explains meaning
int daysBeforeAccountExpires = 7;
The better variable name reduces the need for a comment. Good names and good comments work together, but names should carry as much meaning as possible.
Commenting Out Code
During debugging, developers sometimes comment out code temporarily.
// Console.WriteLine("Temporary debug message");
This is fine for quick experiments, but commented-out code should not stay in a clean codebase for long. Version control already stores old code history. Dead commented code makes files messy and confusing.
TODO Comments
TODO comments mark work that still needs to be done.
// TODO: Validate email format before saving user profile.
TODO comments can be useful, but they should not become permanent forgotten notes. In professional projects, important TODOs should usually be tracked in issues, tickets, or project management tools.
XML Tags Commonly Used in C# Comments
| Tag | Purpose |
|---|---|
<summary> | Short description of a type or member. |
<param> | Describes a method parameter. |
<returns> | Describes the return value. |
<remarks> | Provides extra explanation. |
<exception> | Documents exceptions that may be thrown. |
These comments are especially useful for libraries, APIs, shared code, and public methods that other developers will call.
How IDEs Use XML Comments
One practical advantage of XML documentation comments is IDE support. When a method has proper XML comments, editors can show the summary, parameter information, and return description in tooltips or IntelliSense popups. This helps other developers understand how to call the method without opening its full implementation.
This is especially valuable in shared libraries. A developer using your class can hover over a method and quickly see what it does, what parameters it expects, and what value it returns. Good XML comments improve developer experience without changing runtime behavior.
Generating Documentation from Comments
C# projects can be configured to generate XML documentation files during build. These files can then be used by documentation tools or distributed with libraries. This is why structured comments matter more in reusable code than in small throwaway programs.
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
When this setting is enabled, missing or incomplete XML comments on public members may also produce warnings depending on project settings.
Comments Should Stay Close to the Code They Explain
A comment should usually appear near the code it explains. If the comment is far away, developers may change the code and forget to update the related explanation. Close comments are easier to maintain because the relationship between note and logic is obvious.
Commenting Business Rules
Comments are most useful when they explain business rules or domain rules that are not obvious from syntax alone. For example, code may reject a refund after a certain time period because of company policy. The calculation may be easy to read, but the policy reason may not be clear without a comment.
// Refunds are blocked after 30 days because payment gateway disputes expire.
if (daysSincePurchase > 30)
{
return false;
}
Comments During Debugging
While debugging, it is normal to add temporary comments, disable a line, or leave a quick note for yourself. The problem starts when those temporary comments remain in the final version of the code. Before committing or publishing code, remove debugging comments that no longer explain useful behavior.
Comments in Code Reviews
In professional code reviews, comments are checked just like code. Reviewers may ask whether a comment is accurate, necessary, outdated, or hiding unclear logic. A misleading comment can be worse than no comment because it gives future developers false confidence about what the code does.
Replacing Comments with Better Names
If a comment only explains a poor name, rename the variable, method, or class instead. Clear names reduce the number of comments needed and make the code readable even when comments are not visible in a quick scan.
// Poor
int x = 30; // maximum login attempts per hour
// Better
int maxLoginAttemptsPerHour = 30;
Where to Place Comments
Place comments before the block they explain when the note applies to multiple lines. Use inline comments only for very short clarification. For public APIs, place XML documentation comments directly above the class, method, property, or constructor. Consistent placement makes comments easier to scan and maintain.
A useful rule is simple: if the reader must stop and ask “why is this code doing this,” a comment may be helpful. If the reader can already understand the intent from good names and simple structure, a comment may be unnecessary.
Common Mistakes with Comments in C#
- Writing comments that repeat obvious code.
- Leaving outdated comments after changing logic.
- Keeping large blocks of commented-out code.
- Using comments to hide poor variable names or messy structure.
- Not documenting public methods that need explanation.
- Writing vague comments such as
// fix laterwithout useful detail.
Do comments affect C# program execution?
No. Comments are ignored by the compiler and do not directly affect how the program runs.
What is the difference between // and /* */ comments?
// creates a single-line comment. /* */ creates a multi-line comment that can span across several lines.
What are XML documentation comments in C#?
XML documentation comments use /// and structured XML tags to document classes, methods, parameters, return values, and APIs.
Best Practices for Comments in C#
- Explain why code exists, not only what it does.
- Use clear variable and method names before adding comments.
- Keep comments short and accurate.
- Update comments when the related code changes.
- Use XML documentation comments for public APIs.
- Remove commented-out dead code before finalizing work.
- Use TODO comments only when they are specific and tracked.
Comments in C# are useful when they add context that code alone cannot show. The best comments help future readers understand decisions, assumptions, warnings, and public contracts without making the source file noisy. Strong comments reduce confusion during future maintenance, debugging, onboarding, refactoring, teamwork, and code reviews. Good comments also preserve project knowledge over time.
`r`nContinue learning C# in order
Follow the topic sequence with the previous and next lesson.