Comments are used in a program to help us understand a piece of code. They are human readable words intended to make the code readable. Comments are completely ignored by the compiler.
In C#, there are 3 types of comments:
//
)/* */
)///
)Single line comments start with a double slash //
. The compiler ignores everything after //
to the end of the line. For example,
int a = 5 + 7; // Adding 5 and 7
Here, Adding 5 and 7
is the comment.
// Hello World Program
using System;
namespace HelloWorld
{
class Program
{
public static void Main(string[] args) // Execution Starts from Main method
{
// Prints Hello World
Console.WriteLine("Hello World!");
}
}
}
The above program contains 3 single line comments:
// Hello World Program
// Execution Starts from Main method
and
// Prints Hello World
Single line comments can be written in a separate line or along with the codes in same line. However, it is recommended to use comments in a separate line.
Multi line comments start with /*
and ends with */
. Multi line comments can span over multiple lines.
/*
This is a Hello World Program in C#.
This program prints Hello World.
*/
using System;
namespace HelloWorld
{
class Program
{
public static void Main(string[] args)
{
/* Prints Hello World */
Console.WriteLine("Hello World!");
}
}
}
The above program contains 2 multi line comments:
/*
This is a Hello World Program in C#.
This program prints Hello World.
*/
and
/* Prints Hello World */
Here, we may have noticed that it is not compulsory for a multi line comment to span over multiple lines./* … */
can be used instead of single line comments.
XML documentation comment is a special feature in C#. It starts with a triple slash ///
and is used to categorically describe a piece of code.. This is done using XML tags within a comment. These comments are then, used to create a separate XML documentation file.
/// <summary>
/// This is a hello world program.
/// </summary>
using System;
namespace HelloWorld
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
The XML comment used in the above program is
/// <summary>
/// This is a hello world program.
/// </summary>
The XML documentation (.xml file) generated will contain:
<?xml version="1.0"?>
<doc>
<assembly>
<name>HelloWorld</name>
</assembly>
<members>
</members>
</doc>
Comments are used to explain parts of code but they should not be overused .
For example:
// Prints Hello World
Console.WriteLine("Hello World");
Using comment in the above example is not necessary. It is obvious that the line will print Hello World. Comments should be avoided in such cases.
#csharp #c#