DEV Community

Cover image for What are the Basics of Comments in C#
Emmanuel Pangan
Emmanuel Pangan

Posted on • Updated on

What are the Basics of Comments in C#


Watch the full video on YouTube.

1️⃣ Single-line Comment

It is easy to write a Single-line comment.👩‍💻

Just type two fore-slash or forward slashes(/). And you can write whatever you want. But, the lines above and below are unaffected.

// Single-line Comment
Console.WriteLine("Above");
// Whatever you want.
Console.WriteLine("Below");
Enter fullscreen mode Exit fullscreen mode

You can also add it beside the code, or on top to add a short description.

// Calculates the next leap year.
var nextLeapYear = DateTime.Now.AddYears(4); // Description here.
Enter fullscreen mode Exit fullscreen mode

There’s no rule to add space between fore-slash and the comment, but this is more readable:

// Calculates the next leap year.
Enter fullscreen mode Exit fullscreen mode

than this:

//Calculates the next leap year.
Enter fullscreen mode Exit fullscreen mode

2️⃣ Multi-line Comment

If a Single-line comment isn’t enough:

// TODO: 1. Optimize this code. 2. Google or go to StackOverflow. 3. Copy-paste the code. 4. Refactor again.
Enter fullscreen mode Exit fullscreen mode

Try Multi-line comments. Type fore-slash then asterisk(*), and press Enter. You can end this by typing a closing fore-slash.

/*
 * Multi
 * Line
 * Comment
 */
Enter fullscreen mode Exit fullscreen mode

Pretty useful for TODO lists like for the example earlier.

/*
 * TODO: 
 * 1. Optimize this code. 
 * 2. Google or go to StackOverflow. 
 * 3. Copy-paste the code. 
 * 4. Refactor again.
 */
Enter fullscreen mode Exit fullscreen mode

🧱 Blocks of code: Commenting and Uncommenting

Press CTRL + K + C to comment your codes. It’s really handy when you have a huge chunk of code like this one:

//public double GetFruitPrice(string fruitName)
//{
//    const int FRUIT_NAME_NOT_FOUND = -1;
//    switch (fruitName)
//    {
//        case "Apple":
//            return 5.99;
//        case "Banana":
//            return 3.99;
//        case "Grapes":
//            return 7.99;
//    }
//    return FRUIT_NAME_NOT_FOUND;
//}
Enter fullscreen mode Exit fullscreen mode

Press CTRL + K + U to uncomment:

public double GetFruitPrice(string fruitName)
{
    const int FRUIT_NAME_NOT_FOUND = -1;
    switch (fruitName)
    {
        case "Apple":
            return 5.99;
        case "Banana":
            return 3.99;
        case "Grapes":
            return 7.99;
    }
    return FRUIT_NAME_NOT_FOUND;
}
Enter fullscreen mode Exit fullscreen mode

Just remember to use comments sparingly because it can produce dead codes.

Here's the final code you can view on GitHub Gist.

And here's the code for commenting and uncommenting that's also available on GitHub Gist

Thanks for reading! 📖

Check out my YouTube channel for more coding tutorials. Happy coding everyone! 🧡

Source(s):
Microsoft's documentation about comments

Top comments (0)