Sunday, July 14, 2024 10:20

Table of contents >> Introduction > Comments in C#

Comments in C#

Sooner or later, you will need comments in C# programs (and any other programming language, for that matter). No doubt about that. You must become accustomed to using comments in your programs that explain the processes that the software executes. This means, in short, messages to yourself (and other programmers) that will help you remember and understand in the future what the program is about and what various bits and parts of it do and behave. The more complex your programs will become, the more harder will be for you to remember what each statement is suppose to do. Because some programs can have hundreds or even thousands of lines of code, you won’t be able to remember what each instruction does.

There are two ways of inserting comments in a C# program. The first one, and the most popular is to place two slashes as in the following example:

single line comments in C#

When the compiler will reach those two slash characters, it will ignore the text that follows until the end of that line. Here is an example of using comments inside your programs:

example of C# comments

Reading the above code makes it very easy for you not only to find out relevant information about the program itself and its creator, but also about what each instruction does.

The second way of inserting a comment is to comment an entire block of code, like this:

C# multi-line comments

In this case, when the compiler encounters the /* symbols, it will ignore all the text until the closing symbols of that block comment, */. Using this kind of comment makes it easy to comment fast entire parts of our program, for testing or debugging purposes, for instance.

As a general rule, better comment too much than not comment at all. And no matter how sure you feel that “Ha! I can’t possibly forget what I meant in this code!”, trust me, you will!

The concepts explained in this lesson are also shown visually as part of the following video:


Leave a Reply

Follow the white rabbit