16
C# For Beginners - Lesson 2: Comments
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!");
Run the code above after typing it inside the code box. My first program
won't show up on the displayed output.
![](https://res.cloudinary.com/practicaldev/image/fetch/s--FM1r85Xi--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j8rwt4zvzoeofox6738p.png)
You can also write comments inline using //
.
// My first program
Console.WriteLine("Hello, World!"); // this prints out a message
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.");
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");
Challenge
Add some comments to your answers to the Lesson 1 challenges!
16