C# Comments

In C#, comments are used to explain code, make it more readable, and prevent execution of certain lines during testing or debugging.

Comments are ignored by the compiler and do not affect program execution.

Types of Comments in C#

  • Single-line comments
  • Multi-line comments
  • XML documentation comments

1. Single-line Comments

Single-line comments start with // and extend to the end of the line.


// This is a single-line comment
Console.WriteLine("Hello World"); // Prints output
    

Use Case: Short explanations or notes

2. Multi-line Comments

Multi-line comments start with /* and end with */. They can span multiple lines.


/*
This is a multi-line comment
Used for longer explanations
*/
Console.WriteLine("C# Comments");
    

Use Case: Large descriptions or temporarily disabling blocks of code

3. XML Documentation Comments

XML comments start with /// and are used to generate documentation for classes, methods, and parameters.


/// 
/// Displays a welcome message
/// 
void ShowMessage()
{
    Console.WriteLine("Welcome!");
}
    

These comments are commonly used in professional and enterprise-level applications.

Comment Comparison

Comment Type Syntax Purpose
Single-line // Brief explanation
Multi-line /* */ Detailed explanation
XML /// Documentation

Best Practices

  • Write clear and meaningful comments
  • Avoid obvious or redundant comments
  • Keep comments updated with code changes
  • Use XML comments for public methods and classes

Conclusion

Comments improve code readability and maintainability. Proper use of comments makes code easier to understand for developers.

C# Comments Quiz

Q1. Which symbol is used for single-line comments?



Q2. Which comment is used for documentation?



Q3. Which comment can span multiple lines?


C# Introduction C# Variables & Keywords C# Data Types C# If Else Statement C# Loops C# Comments C# Type Casting C# User Input C# Operators C# Math C# String C# OOP Concepts C# Classes and Objects C# Multiple Classes and Objects C# Class Members C# Constructors C# Access Modifiers