C# Comments
Introduction
Comments are non-executable text included in code to provide explanations, notes, or documentation. In C#, comments are crucial for making your code more understandable to yourself and others who might read or maintain it in the future. They serve as documentation within your source code, explaining the purpose of variables, methods, classes, or complex algorithms without affecting how the program runs.
In this lesson, we'll explore different types of comments in C#, best practices for writing effective comments, and see how they can improve the overall quality of your code.
Types of Comments in C#
C# supports three main types of comments:
- Single-line comments
- Multi-line comments
- XML documentation comments
Let's look at each type in detail.
1. Single-Line Comments
Single-line comments begin with two forward slashes (//
) and continue until the end of the line. Everything after the slashes on that line is ignored by the compiler.
// This is a single-line comment
int age = 25; // This comment appears after some code
Single-line comments are useful for short explanations or for temporarily disabling a line of code (known as "commenting out" code).
2. Multi-Line Comments
Multi-line comments (also called block comments) start with /*
and end with */
. Everything between these delimiters is ignored by the compiler, regardless of how many lines it spans.
/* This is a multi-line comment
that can span across several lines.
The compiler will ignore all text
until it reaches the closing delimiter. */
int totalScore = 95;
Multi-line comments are ideal for longer explanations or when you need to comment out multiple lines of code temporarily.
3. XML Documentation Comments
XML documentation comments are special comments that can be used to generate documentation for your code. They begin with three forward slashes (///
) and contain XML tags.
/// <summary>
/// Calculates the sum of two integers.
/// </summary>
/// <param name="a">First integer value</param>
/// <param name="b">Second integer value</param>
/// <returns>The sum of a and b</returns>
public int Add(int a, int b)
{
return a + b;
}
XML comments are particularly useful for documenting methods, properties, classes, and other code elements in a structured way that can be processed by documentation tools like DocFX or Sandcastle.
When and How to Use Comments
Good Commenting Practices
- Explain Why, Not What: Your code should be clear enough to show what it's doing, but comments should explain why you're doing it.
// BAD: Increment counter by 1
counter++;
// GOOD: Increment the visitor count to keep track of page views
counter++;
- Comment Complex Logic: If a section of code implements a complex algorithm or business rule, a comment can help readers understand the logic.
// Calculate discount using tiered pricing structure:
// - Orders > $1000 get 10% discount
// - Orders > $5000 get 15% discount
// - Orders > $10000 get 20% discount
if (orderTotal > 10000)
{
discount = 0.2m;
}
else if (orderTotal > 5000)
{
discount = 0.15m;
}
else if (orderTotal > 1000)
{
discount = 0.1m;
}
else
{
discount = 0;
}
-
Keep Comments Updated: Outdated comments can be misleading. Always update comments when you change the corresponding code.
-
Use Comments for TODO Items: Mark incomplete work or areas that need improvement.
// TODO: Optimize this algorithm for better performance
for (int i = 0; i < largeArray.Length; i++)
{
// Existing implementation...
}
Complete Example: Comments in Action
Let's see a comprehensive example showing all types of comments in a practical scenario:
using System;
namespace CommentDemo
{
/// <summary>
/// Represents a bank account with basic operations.
/// </summary>
public class BankAccount
{
// Fields to store account information
private string accountNumber;
private decimal balance;
private string ownerName;
/// <summary>
/// Initializes a new bank account with specified details.
/// </summary>
/// <param name="accountNumber">The unique account identifier</param>
/// <param name="ownerName">Name of the account holder</param>
/// <param name="initialBalance">Starting balance amount</param>
public BankAccount(string accountNumber, string ownerName, decimal initialBalance = 0)
{
this.accountNumber = accountNumber;
this.ownerName = ownerName;
/* Initial balance cannot be negative according to
bank policy section 3.2 updated on Jan 2023 */
this.balance = initialBalance >= 0 ? initialBalance : 0;
}
/// <summary>
/// Deposits money into the account.
/// </summary>
/// <param name="amount">The amount to deposit</param>
/// <returns>True if the deposit was successful</returns>
public bool Deposit(decimal amount)
{
// Reject negative deposits
if (amount <= 0)
{
return false;
}
balance += amount;
return true;
}
/// <summary>
/// Withdraws money from the account if sufficient funds are available.
/// </summary>
/// <param name="amount">The amount to withdraw</param>
/// <returns>True if the withdrawal was successful</returns>
public bool Withdraw(decimal amount)
{
// Check for valid amount and sufficient funds
if (amount <= 0 || amount > balance)
{
return false;
}
// TODO: Add transaction fee calculation based on account type
balance -= amount;
return true;
}
/// <summary>
/// Gets the current account balance.
/// </summary>
/// <returns>The current balance</returns>
public decimal GetBalance()
{
return balance;
}
}
class Program
{
static void Main(string[] args)
{
// Create a new account with $1000 initial balance
BankAccount account = new BankAccount("12345", "John Doe", 1000);
// Perform some transactions
account.Deposit(500); // Balance should be $1500
account.Withdraw(200); // Balance should be $1300
// Display the current balance
Console.WriteLine($"Current balance: ${account.GetBalance()}");
}
}
}
Output:
Current balance: $1300
Commenting for Better IntelliSense
One often overlooked benefit of XML comments is that they appear in IntelliSense (the code completion feature) in many IDEs like Visual Studio. This helps developers understand how to use your methods while they are coding.
When you hover over a method that has XML comments, the IDE will display the summary and parameter information:
/// <summary>
/// Sends an email to the specified recipient.
/// </summary>
/// <param name="recipient">Email address of the recipient</param>
/// <param name="subject">Subject line of the email</param>
/// <param name="body">Content of the email</param>
/// <returns>True if the email was sent successfully</returns>
public bool SendEmail(string recipient, string subject, string body)
{
// Email sending implementation...
return true;
}
When another developer uses this method, they'll see all this helpful information as they type.
Using Comments for Code Organization
Comments can also be used to organize your code into logical sections:
public class UserManager
{
//==============================================
// User Authentication Methods
//==============================================
public bool Login(string username, string password)
{
// Implementation...
}
public void Logout()
{
// Implementation...
}
//==============================================
// User Profile Management
//==============================================
public bool UpdateProfile(UserProfile profile)
{
// Implementation...
}
// And so on...
}
This approach creates visual breaks in your code that make it easier to navigate, especially in larger files.
Summary
Comments in C# are a vital tool for making your code more understandable and maintainable. We've covered:
- Single-line comments (
//
) for brief explanations - Multi-line comments (
/* */
) for longer descriptions - XML documentation comments (
///
) for generating formal documentation - Best practices for writing effective comments
- How comments can improve developer experience through IntelliSense
- Using comments for code organization
Remember that the best code is self-documenting, with clear variable names and logical structure. Comments should complement your code, not compensate for confusing or poorly written code. When used effectively, comments make your code more accessible to others and to your future self.
Exercises
- Add appropriate comments to a method that calculates compound interest.
- Convert regular comments in a class file to XML documentation comments.
- Review a code file and identify comments that don't add value (they just restate what the code obviously does).
- Practice using region comments (
#region
and#endregion
) to organize a large C# class.
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)