C#

C# Comments

C# Comments are only for you to read, not for the computer to execute. All the comments displayed in the Code Editor are green by default, which makes it easy to identify those lines, and the C# compiler ignores those parts when it runs your program.

Use C# comments only to clarify code that’s difficult to understand. The developer writes comments while writing code so that if another developer needs to edit this code, he or she is able to understand the code easily, thus making future changes to your code much easier.

Single-Line Comments in C#

You can make any line into a C# single-line comment by starting it with the two forward slash marks //, indicating that the remainder of the line is a comment. Once the compiler reads the slashes that start the comment, it ignores all characters until the end of the current line. In other words, all the text placed after // will be treated as a single line comment.

// This is a comment
Console.WriteLine("This is not a comment");

Run Demo

If you run these two lines, you’ll get the following output: This is not a comment

The first line is ignored when the program runs. The comment, which starts with //, is only for you and other people reading the code.

// int age = 35;
Console.WriteLine(age); // Error

Compiler ignored first line of code and used it as a comment.

Run Demo

End-Of-Line Comments in C#

You can also put comments at the end of a line of code, like this:

int variableName = 1; //this is a comment

Run Demo

Everything before // is a normal line of code, and everything after that is a comment.

Multi-Line Comments ( Delimited comments )

Sometimes, you may want to use more than one line for comments without having to have // characters at the beginning of each line. C# multiline comment can be split over several lines. This type of comment begins with an open comment mark /* and ends with a closed comment mark */. All the text between the delimiters is ignored by the compiler. You can see the example below.

/*
Comment Line 1
Comment Line 2
*/

/*********************
* Comment Line 1
* Comment Line 2
**********************/

Run Demo

C# Multiline comments are good for making sections of your code stand out visually when you’re reading it. You can use them to describe what’s going on in a section of code.

Sending
User Rating 5 (1 vote)

Tagged in :

Send this to a friend