C# Comments


When writing code, you might want to add some text that will serve as a reminder or a note for you or for anyone who will read your code. In C# (and most programming languages), you can do that using comments. Comments add documentation or notes to anyone who will read your code including yourself. Comments are ignored by the compiler and are not part of the actual C# code. Suppose you want to describe what a particular code is going to do, then you can place a comment above or beside it. Here is an example of a program with a comment:

namespace CommentsDemo
    class Program
        public static void Main(string[] args)
            // This line will print the message hello world
            System.Console.WriteLine("Hello World!");

Line 7 shows an example of a single line comment. There are two types of comments, single line comments and multiline comments as presented below:

// single line comment
/* multi 
 comment */

Single line comments, as the name implies, are used for commenting a single line of code. A single line comment starts with // and everything after // will be part of the comment. Single line comments are often placed above or to the right of a single line of code. These comments are ideal for describing the functionality for a single line of code.

If your comment is longer and requires multiple lines, use the multiline comment. A multiline comment starts with /* and ends with */. Everything between /* and */ will be considered as comments. This type of comment is useful for adding details about the program at the source code’s header or any long comments that spans multiple lines.

There is another type of comment which is called XML comment. It is represented by three slashes (///). It typically functions as a single line comment but it is commonlly used for creating documenation for your code. You will learn more about XML comment and how to use it in a separate lesson.