Comments are an important part of the code. They allow developers to explain their code, document important information and make the code easier to understand. Whatever you write in comments, compilers ignore it and do not execute them.
For writing good and productive comments please remember the points mentioned below:
- Comments are self-explanatory. Comments should add value by explaining complex or non-obvious logic.
- Comments should be clear and concise. Avoid writing overly complex comments that could confuse the reader.
Example:
using System;
class Program
{
static void Main()
{
// A comment to provide information about below line
// Print statement
Console.WriteLine("GFG!");
}
}
Output
GFG!
In C#, There are three types of comments which are defined below:
1. Single-Line comments
A single-line comment in C# is used to add a brief explanation or note about a specific line of code. This type of comment starts with two forward slashes (//) and continues until the end of the line. Example:
using System;
class Program
{
static void Main()
{
// Single line comment
Console.WriteLine("GFG!");
}
}
Output
GFG!
2. Multi-Line Comments
A multi-line comment is used to comment out a block of code that spans multiple lines. It begins with /* and ends with */. Everything between these symbols is considered part of the comment and not executed by the compiler. Example:
using System;
class Program
{
static void Main()
{
/* Multi line comment which
will be ignored by the compiler
*/
Console.WriteLine("GFG!");
}
}
Output
GFG!
3. XML Comments
In C#, XML comments are a special kind of documentation comment that you write directly in the source code. They’re written using triple slashes (///) and allow you to describe classes, methods, properties, parameters and other members. They are used by tools like Visual Studio to provide IntelliSense and can also generate external documentation. Example:
using System;
class Calculator
{
/// <summary>
/// Adds two numbers
/// </summary>
/// <param name="a">First number</param>
/// <param name="b">Second number</param>
/// <returns>Sum of two numbers</returns>
public int Add(int a, int b)
{
return a + b;
}
}
class Program
{
static void Main()
{
Calculator obj = new Calculator();
Console.WriteLine(obj.Add(5, 5));
}
}
Output
10
Note: The compiler ignores comments during compilation. They are not converted into intermediate language (IL) code and do not affect the execution of the program.
Tip:
- Shortcut for single line: Ctrl + /
- Shortcut for multi-line: Select lines and press Ctrl + /