C# Comments

C# Comments: Documenting Your Code

Comments are lines of text in your code that are completely ignored by the compiler. They are used to explain what the code is doing, make it more readable for other developers, and prevent execution of specific lines of code during testing.

In C#, there are two main types of comments: single-line comments and multi-line comments.


1. Single-Line Comments

Single-line comments start with two forward slashes //. Any text following // on that specific line will be ignored by C#.

Single-Line Comment Example

using System;

class Program { static void Main() { // This is a comment Console.WriteLine("Hello World!"); Console.WriteLine("Learning C#"); // This is a comment at the end of a line } }


2. Multi-Line Comments

Multi-line comments start with /* and end with */. Any text between these two markers will be ignored by the compiler. This is incredibly useful when you need to write a long explanation or comment out large blocks of code.

Multi-Line Comment Example

using System;

class Program { static void Main() { /* The code below will print the words Hello World to the screen, and it is amazing */ Console.WriteLine("Hello World!"); } }


3. XML Documentation Comments

In C#, there is a third, special type of comment called an XML Documentation Comment, which starts with three forward slashes ///.

These are placed directly above classes or methods, and they are used to generate official documentation for your code. The Visual Studio IDE uses these comments to show helpful tooltips when you (or other developers) are typing out method names.

XML Comment Example

using System;

class Program { /// <summary> /// This is the main entry point for the application. /// </summary> static void Main() { Console.WriteLine("Hello World!"); } }


Best Practices for Commenting

Exercise

?

Which syntax is used to create a single-line comment in C#?