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:
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 classclass HelloWorld{// main functionstatic void Main(){// A single line comment: print hello worldSystem.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#.
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 simpleHelloWorld class*/class HelloWorld{/*This is themain function*/static void Main(){/*This is a multiline commentin C#*/System.Console.WriteLine("Hello, World!");}}
As seen in the above example of multi-line comments, everything is ignored between /*
and */
.