DEV Community

loading...

C# For Beginners - Lesson 2: Comments

Kristina (Coding Mama)
Helping others learn C#! I love cats 🐱, coffee β˜•, and the colour pink πŸ’•!
Originally published at codingmama.gitbook.io ・Updated on ・2 min read

At the end of this lesson, you should be able to answer the following:

  • What are comments? Why should I use them?
  • How do I write comments in C#?

Programs are written for computers, but sometimes we need to add more context to help other programmers read and understand our code. (Sometimes that programmer is ourselves!)

To do this, we can write comments in our program. Comments are lines of text that are ignored by C# when the program is run.

Good code is usually self-explanatory, but comments are useful to explain why a program has been written a certain way.

To write a comment, type //, followed by the comment. Everything after the // is ignored until the next line.

// My first program
Console.WriteLine("Hello, World!");
Enter fullscreen mode Exit fullscreen mode

Run the code above after typing it inside the code box. My first program won't show up on the displayed output.

Comments

You can also write comments inline using //.

// My first program
Console.WriteLine("Hello, World!"); // this prints out a message
Enter fullscreen mode Exit fullscreen mode

Comments are also useful to take out bits of code you don't want to run. For example, if you're trying to find the cause of an error in your code (also called debugging), you can comment out the code that you want to make sure is not causing the error.

Console.WriteLine("Yesterday it worked.");
Console.WriteLine("Today it is not working.");
// Console.WriteLine("This line will not print.");
Console.WriteLine("Coding is like that.");
Enter fullscreen mode Exit fullscreen mode

Another way to write comments is the multi-line comment. As the name suggests, you can use it to write comments that span multiple lines.

The multi-line comment starts with /* and ends with */. Everything between these two elements is ignored.

Console.WriteLine("My favourite dinosaurs:");
Console.WriteLine("Triceratops");
Console.WriteLine("Velociraptor");
/*
Console.WriteLine("Mosasaurus");
Console.WriteLine("Dimetrodon");
Console.WriteLine("Pteranodon");
*/
Console.WriteLine("Apatosaurus");
Console.WriteLine("Tyrannosaurus Rex");
Enter fullscreen mode Exit fullscreen mode

Challenge

Add some comments to your answers to the Lesson 1 challenges!

Discussion (0)