C# For Beginners
Search…
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.
1
// My first program
2
Console.WriteLine("Hello, World!");
Copied!
Run the code above after typing it inside the code box. My first program won't show up on the displayed output.
You can also write comments inline using //.
1
// My first program
2
Console.WriteLine("Hello, World!"); // this prints out a message
Copied!
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.
1
Console.WriteLine("Yesterday it worked.");
2
Console.WriteLine("Today it is not working.");
3
// Console.WriteLine("This line will not print.");
4
Console.WriteLine("Coding is like that.");
Copied!
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.
1
Console.WriteLine("My favourite dinosaurs:");
2
Console.WriteLine("Triceratops");
3
Console.WriteLine("Velociraptor");
4
/*
5
Console.WriteLine("Mosasaurus");
6
Console.WriteLine("Dimetrodon");
7
Console.WriteLine("Pteranodon");
8
*/
9
Console.WriteLine("Apatosaurus");
10
Console.WriteLine("Tyrannosaurus Rex");
Copied!
Challenge
Add some comments to your answers to the Lesson 1 challenges!
Last modified 4mo ago
Copy link