In programming languages, comments are used to understand a piece of code and what it will do when it is executed.
In C#, there are 3 types of comments.
The single line or one line comment is the most basic type of comment in C#. It is started with two forward slashes (//
) and lasts until the end of the line.
Let's consider the following example.
// Initialize the counter
int counter = 0;
// Execute the loop body while the loop condition holds
while (counter <= 5)
{
// Print the counter value
Console.WriteLine("Number: " + counter);
// Increment the counter
counter++;
}
Here you can see that we have added a single line comment for each statement which explains what it does. You can also use a single-line comment at the end of a line of code as shown below.
Console.WriteLine("Number: " + counter); // Print the counter value
counter++; // Increment the counter
The multiline or multiple line comments are used to comment on more than one line. You can start multiline comment by specifying /*
and end with */
, so everything in between these character sequences is treated as comments.
//
at the start of each line./* This a parameterized constructor which takes the following parameters
- id
- name
- address
It will initialize the employee object with values passed as parameters.
*/
public Employee(int id, string name, string address)
{
this.Id = id;
this.Name = name;
this.Address = address;
}
/*
for (int i = 0; i <= 10; i++)
{
if (i > 3 && i < 8)
continue;
Console.WriteLine("Counter: {0}", i);
}
*/
Console.WriteLine(" Entire code block is commented");
XML documentation comments are a special kind of comment, added above the definition of any user-defined type or member.
/// <summary>
/// Method to print all the information on console window.
/// </summary>
public void Print()
{
Console.WriteLine("Id: {0}, Name: {1}, Address: {2}", this.Id, this.Name, this.Address);
}
For more information, see the official page for Documenting your code with XML comments
All the examples related to the comments are available in the Comments.cs
file of the source code. Download the source code and try out all the examples for better understanding.