C# Comments
Document and explain your code
💬 C# Comments
Comments are notes in your code that the compiler ignores. They help explain what your code does, making it easier for you and others to understand.
using System;
class Comments
{
static void Main()
{
// This is a comment
Console.WriteLine("Hello!"); // Print greeting
}
}
Output:
Hello!
Types of Comments
Single-Line
Comment one line of text
// This is a comment
int x = 5;
Multi-Line
Comment multiple lines
/* This is
a multi-line
comment */
XML Documentation
Create documentation
///
/// Adds two numbers
///
Disable Code
Temporarily turn off code
// Console.WriteLine("Off");
Console.WriteLine("On");
🔹 Single-Line Comments
Single-line comments start with // and are ignored by the compiler, useful for brief explanations. They help document code logic, assumptions, or temporary notes on a single line, such as // Calculate total price. This improves readability and aids future maintenance.
using System;
class SingleLineComments
{
static void Main()
{
// This is a single-line comment
Console.WriteLine("Hello");
// You can explain what the code does
int age = 25; // Store the age
// Comments can be on their own line
// or at the end of a code line
string name = "John"; // User's name
Console.WriteLine(name + " is " + age);
}
}
Output:
Hello
John is 25
🔹 Multi-Line Comments
Multi-line comments, enclosed between /* and */, span several lines and are ideal for longer descriptions. They document complex logic, function purposes, or disable code blocks during debugging. For example, outlining algorithm steps or temporarily removing unused code sections.
using System;
class MultiLineComments
{
static void Main()
{
/* This is a multi-line comment.
It can span multiple lines.
Useful for longer explanations. */
Console.WriteLine("Program started");
/*
This code is commented out:
int x = 10;
int y = 20;
Console.WriteLine(x + y);
*/
/* You can also use it for short comments */
int result = 5 * 5;
Console.WriteLine("Result: " + result);
}
}
Output:
Program started
Result: 25
🔹 XML Documentation Comments
XML documentation comments use /// and generate structured, tooltip-friendly documentation in IDEs. They describe classes, methods, parameters, and returns, supporting auto-generated documentation tools. For example, /// <summary>Calculates the sum.</summary> provides clear API references.
using System;
class XmlComments
{
///
/// Calculates the sum of two numbers
///
/// First number
/// Second number
/// The sum of a and b
static int Add(int a, int b)
{
return a + b;
}
///
/// Main entry point of the program
///
static void Main()
{
int result = Add(10, 20);
Console.WriteLine("Sum: " + result);
}
}
Output:
Sum: 30
🔹 Commenting Out Code
Commenting out code temporarily disables it without deletion, aiding debugging and testing. By prefixing lines with // or wrapping with /* */, you can isolate issues or test alternatives. This preserves original logic while experimenting, ensuring reversible changes.
using System;
class CommentingOut
{
static void Main()
{
Console.WriteLine("This runs");
// Console.WriteLine("This is disabled");
// int x = 10;
/*
Console.WriteLine("This block is disabled");
int y = 20;
Console.WriteLine(y);
*/
Console.WriteLine("This also runs");
// Uncomment to enable:
// Console.WriteLine("Enable me!");
}
}
Output:
This runs
This also runs
🔹 Best Practices
Effective commenting involves clarity, relevance, and maintenance. Write comments that explain why, not what. Avoid obvious statements, update comments with code changes, and use consistent style. Good comments enhance collaboration, readability, and long-term code maintainability.
Do:
- Explain WHY: Why you chose this approach
- Clarify complex logic: Help others understand tricky code
- Document functions: Explain parameters and return values
- Keep updated: Update comments when code changes
Don't:
- State the obvious: Don't comment what's already clear
- Write novels: Keep comments concise
- Leave old comments: Remove outdated comments
- Comment bad code: Rewrite unclear code instead
🔸 Good Comments:
// Calculate discount for bulk orders (10+ items)
if (quantity >= 10)
{
price = price * 0.9; // Apply 10% discount
}
// Using binary search for better performance
int index = BinarySearch(array, target);
🔸 Bad Comments:
// Increment i by 1
i++; // BAD: Too obvious
// This is a variable
int x = 5; // BAD: States the obvious
// TODO: Fix this later
// Broken code here // BAD: Don't leave broken code
🔹 Practical Example
Here's a well-commented program that demonstrates good commenting practices:
using System;
///
/// Simple calculator program
///
class Calculator
{
static void Main()
{
// Get two numbers from user
Console.Write("Enter first number: ");
int num1 = int.Parse(Console.ReadLine());
Console.Write("Enter second number: ");
int num2 = int.Parse(Console.ReadLine());
// Perform calculations
int sum = num1 + num2;
int difference = num1 - num2;
int product = num1 * num2;
// Display results
Console.WriteLine("\nResults:");
Console.WriteLine($"Sum: {sum}");
Console.WriteLine($"Difference: {difference}");
Console.WriteLine($"Product: {product}");
/* Division requires special handling
to avoid divide-by-zero errors */
if (num2 != 0)
{
double quotient = (double)num1 / num2;
Console.WriteLine($"Quotient: {quotient:F2}");
}
else
{
Console.WriteLine("Cannot divide by zero");
}
}
}