C# comments (or comments in any programming language, for that matter) are pieces of text that you add to a program in order to communicate something to a human reader. That’s pretty much it.
The compiler ignores comments. Don’t worry about comments slowing down performance. Comments do contribute to the overall size of the source code, but that shouldn’t concern you either. Disk space gets cheaper each year, and so does internet connection. You don’t need to lose sleep over a handful of extra bytes being stored and transmitted.
Single Line Comments
Single line comments are exactly what their name suggests: comments that span a single line. To start a single line comment, you use two forward slashes (//). Everything that comes after is considered a comment. Here’s an example:
1 2 3 4 5 |
// the following line will be ignored: // Console.WriteLine("Preparing to say Hello World"); Console.WriteLine ("Hello World"); // this will be printed |
If you run the code above, you’ll see just “Hello World” on the screen. As you can see, you can place a single line comment either after a regular line of code or on its own dedicated line. It makes no difference whatsoever in regard to the final result, but it’s considered a convention to place them on dedicated lines.
Multi-Line Comments
Next, we have another very descriptive name. Multi-line comments are comments that span multiple lines. You start such a comment with the “/” delimiter and end it with the “/” delimiter. Everything inside the delimiters is a comment. Consider the following example:
1 2 3 4 5 6 7 8 9 |
/* if you run this code, you're going to see two sentences on the screen. First, you're going to see "Preparing to say Hello World". On the next line, you'll see "Hello World". */ Console.WriteLine("Preparing to say Hello World"); Console.WriteLine ("Hello World"); |
Bear in mind that multi-line comments, despite their name, aren’t obligated to really span multiple lines. For instance, let’s rewrite the example we used with single line comments using the multi-line delimiters:
1 2 3 4 5 |
/* the following line will be ignored: */ /* Console.WriteLine("Preparing to say Hello World"); */ Console.WriteLine ("Hello World"); /* this will be printed */ |