How to add comments in C#

All across programming languages, we can not underestimate the power of comments. Comments in a code can make it more readable, make code maintenance much easier, prevent execution during tests or debugging, etc.

In C#, there are two types of comments:

  1. Single-line comments
  2. Multi-line comments

Single-line comments

Single-line comments are the easiest to implement. It begins with just two forward slashes(//). As the name implies it starts and ends on a single line. And as we should know, anything after // is ignored in C#.

In the example below we demonstrated the use of a single-line comment:

// a HelloWorld class
class HelloWorld
{
// main function
static void Main()
{
// A single line comment: print hello world
System.Console.WriteLine("Hello, World!");
}
}

As seen above, the text "A single line comment: print hello world", including other single comments in the code, are ignored in C#.

Multi-line comments

Unlike single-line comments that take only a single line, multi-line comments span multiple lines, thus the name. It starts with a forward slash and an asterisk (/*) and ends with the same asterisk and a forward slash too (*/). Anything between these is ignored.

Let’s have a look at the multi-line comments example below.

/*
Create a simple
HelloWorld class
*/
class HelloWorld
{
/*
This is the
main function
*/
static void Main()
{
/*
This is a multiline comment
in C#
*/
System.Console.WriteLine("Hello, World!");
}
}

As seen in the above example of multi-line comments, everything is ignored between /* and */.