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 should be self-explanatory. Comments should add value by explaining complex or non-obvious logic.
- Comments should be clear and concise.
using System;
class GFG
{
static void Main()
{
// A comment to provide information about below line
// Print statement
Console.WriteLine("GeeksForGeeks!");
}
}
Output
GeeksForGeeks!Types of comments
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.
Syntax:
// This is a single-line comment
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 write comments that span multiple lines. It begins with /* and ends with */. Everything between these symbols is treated as a comment.
Syntax:
/*
This is a
multi-line comment*/
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
XML documentation comments are special comments used to document C# code. They start with three forward slashes (///) and commonly use XML tags such as
These comments can be used by IDEs such as Visual Studio to display documentation through IntelliSense and can also be processed to generate XML documentation files.
Syntax:
///
/// Description of the member
///
using System;
class Calculator
{
///
/// Adds two numbers
///
/// First number
/// Second number
/// Sum of two numbers
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 + /