C# Comments

In this lesson, you will learn about comments in C#, their importance, along with examples to better understand the topic.


What are comments in C#?

In C#, developers use comments to leave a comment/note about a piece of code. In other words, comments, which are ignored by the compiler, are used to explain the code, making it easier to understand what it does.


Type of comments in C#

In C#, there are three types of comments:

  • Single-line comment
  • Multiple line comment
  • XML comment

Single line-comment

A single-line comment is a comment that starts with the // and remains in a single line.

Example of single line comment in C#

// This program prints the Hello World! String to the console
using System;
class Learnmodo
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!"); // Prints the output
    }
}

Multiple line comments

A multiple line comments start with */ and end with */. the main purpose of the multiple-line comment is to have a comment with more than one line.

Example of multi-line comment in C#

using System;
class Learnmodo
{
    /*
    Program Explanation:
    This program prints the "Hello World!" string to the console.
    It takes no argument.
    */
    static void Main(string[] args)
    {

        Console.WriteLine("Hello World!");
    }
}

XML comment

This type of comment is used at the top of class declaration and functions. By default, it contains information about a function scope, parameters, and return values. Users can enter their extra information in the XML comment if they desire.

You can generate an XML comment by typing the forward slash three times (///). The cursor must be right before a class or function.

Example of XML comment in C#

using System;
class Learnmodo
{
    /// <summary>
    /// This program prints the "Hello World!" string to the console.
    /// </summary>
    /// <param name="args"></param>
    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
    }
}

XML comments are a great feature that enriches your application for code management. It creates IntelliSense that make the developers’ life easier, as shown below:

This concludes the C# Comments lesson. In the next lesson, you will learn about how to output data in C#.