© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
G. ByrneTarget C#https://doi.org/10.1007/978-1-4842-8619-7_5

5. Commenting Code

Gerard Byrne1  
(1)
Belfast, Ireland
 

We learned in Chapter 4 that our application code can involve input and output and that the input and output can be completed in the console window. The output from our application is the visible part for an end user and it is important they have a good experience when seeing the output. The user experience is often referred to as the UX and can involve the developer making use of colors, emphasis, layout, etc. to make the application readable and pleasing to look at.

This chapter will concentrate on how to create a good user experience for the developer rather than the end user, when they are creating, reading, and maintaining code. It is particularly important to understand that as developers we should be having a good user experience when we look at any application code, whether it is our code or someone else's.

As a starting point, we will state that one of the current themes in the domain of programming in the commercial environment is writing self-documenting code . This is a great idea and one that we can achieve by writing C# code statements that will be easily understood by other developers who will read, use, or maintain the code. In fact, it can even make the original writer of the code, us, understand it better when returning to it to make amendments. We should always keep the strategy of self-documenting code foremost in our thoughts. Writing self-documenting code can be easy to do and can involve simple steps and techniques, which will become “second nature” after a while. These include
  • Adding astutely placed comments as explanations in our code.

  • Not overusing comments. Not everything will need a comment if the code is written well, but comments can be a big help to the reader.

  • Our variable names being such that they explain the variable purpose.

  • Our method names being such that they explain the method purpose.

  • Our class names being such that they explain the purpose of the class.

Another strategy is to use colors in the coding statements. We should have already noticed that the Visual Studio Integrated Development Environment has colored parts of our code. Examples of code coloring are shown in Figure 5-1.

A 19-line code for code coloring in Visual Studio.

Figure 5-1

Visual Studio code coloring

This code coloring within Visual Studio is one way in which Microsoft has attempted to help developers who write and read code.

Note

In the code examples we will use throughout the chapters in this book, there will be lots of comments used to help us understand the code, but if these were commercial applications, we would not have as many comments.

Make sure to read the code comments in the course code examples as they have invaluable information that adds to and supplements the text of this book. They are in the code to help clarify what we are doing and why we are doing certain things. So we should not ignore them. We should read them, but we do not necessarily have to type the comments into our code.

Comments can be used to give information such as
  • A description indicating the purpose of the application

  • Information about the developer or developers

  • The date on which the program was first created

  • The date when maintenance occurred, for example, when lines of code were amended, added, or deleted

  • What a line of code or lines of code are doing

  • The purpose of a method

  • The purpose of a delegate that is linked to a method

  • The purpose or intrinsic workings of a complicated formula

C# Single-Line Comments

Single-line comments in C#, and many other programming languages, are preceded by two forward slash symbols , //. The // indicates a single-line comment, which is generally used for brief comments. Some developers will write the comments above the code, while others will use the comment on the same line as the code. Both types are shown in Listings 5-1, 5-2, and 5-3.

Example 1

Listing 5-1 shows an example of three single-line comments, which could be used at the start of a program to give the user information about the program, the developer, and the creation date. The comments are at the start of the program code before any C# statements are entered.
// Program:   A simple C# program to output text and read input
// Author:    Gerry Byrne
// Date of creation: 01/06/2021
Listing 5-1

Single-line comments

Example 2

Listing 5-2 shows a single-line comment, which gives the user information about the class called Program that follows it. The single-line comment appears above the code statement .
// This is our only class and it will contain the Main method
class Program
Listing 5-2

Single-line comment above code

Example 3

Listing 5-3 shows a single-line comment, which gives the user information about the line of code. In this case the single-line comment appears on the same line as the code statement.
Console.ReadLine(); // This code line waits for the user input
Listing 5-3

Inline comment

Projects and Solutions

Before we start writing the code for this chapter, let us think about the project we created in Chapter 4. When we created it, we gave the project the name ConsoleV1, which was perfectly fine at the time, but definitely not very descriptive. We will talk more about naming later. Now, when we wish to code the example for this chapter, where will we put our code?

Well, we can do this in
  • The existing project in the solution, where we can amend the existing class or create a new class to hold the new code

  • A new folder within the existing project

  • A new project that we can create

For this exercise we will create a new project in the existing solution, and we will rename the existing project to ensure its name fits in with the way we will name all the projects for the chapters in the book. But what should we call the old and new projects? If we think about what we have just talked about, self-documenting code, we should question the name of the project and folders within it. When we created the project in Chapter 4, we called it ConsoleV1, but maybe it should have been named better, for example:
  • ConsoleApplications

  • Coursecode

  • Chapter4

If we decide that a name change would be appropriate, we can rename the project, but will the code in the class need to be changed? No, this will not affect the code in the project.

Rename the ConsoleV1 project:
  1. 1.

    Make sure the solution and project are open in Visual Studio.

     
  2. 2.

    Right-click the ConsoleV1 project name.

     
  3. 3.

    Choose Rename , as shown in Figure 5-2.

     

A Solution Explorer window displays a context menu with the option Rename highlighted.

Figure 5-2

Renaming a C# project

  1. 4.

    Name the project Chapter4.

     
  2. 5.

    Press the Enter key.

     
The project within the solution is now displayed within the Solution Explorer panel with the new name as shown in Figure 5-3. We will not worry for now about the namespace name in the program code.

A Solution Explorer panel displays the project's new name as a C hash sign Program dot c s. The new name is highlighted.

Figure 5-3

Renamed C# project

Add a new project to hold the code for this chapter:
  1. 6.

    Right-click the CoreCSharp solution name in the Solution Explorer panel.

     
  2. 7.

    Choose Add, as shown in Figure 5-4.

     
  3. 8.

    Choose New Project.

     

A Solution Explorer panel displays a context menu with the Add option highlighted. A submenu is also exhibited with the option, New Project highlighted.

Figure 5-4

Adding a new C# project

  1. 9.

    Choose Console App from the listed templates that appear, as shown in Figure 5-5.

     

A window of templates includes C hash sign, Linux, mac O S, Windows, and Console.

Figure 5-5

Selecting a new C# console project

  1. 10.

    Click the Next button.

     
  2. 11.

    Name the project Chapter5, leaving it in the same location, as shown in Figure 5-6.

     

An input box for Project Name has an entry of Chapter 5. A dropdown box for Location has an entry of C, colon, backslash, Core C Sharp, backslash, Core C Sharp.

Figure 5-6

Naming a new C# console project

  1. 12.

    Click the Next button.

     
  2. 13.

    Choose the framework to be used, which in our projects will be .NET 6.0 or higher, as shown in Figure 5-7.

     

A drop-down menu for Framework has two choices, dot Net Core 3.1, long-term support, and dot Net 6.0, long-term support. The second option is highlighted.

Figure 5-7

Choosing the project framework

  1. 14.

    Click the Create button.

     
Now we should see the two projects, Chapter4 and Chapter5, within the solution called CoreCSharp (Figure 5-8).

A Solution Explorer window contains a Solution Core C Sharp with two projects. These are Chapter 4 and Chapter 5.

Figure 5-8

Solution Explorer displaying all projects

New .NET 6 Templates

.NET 6 introduces developers to new code templates when we choose a console application. The “traditional” console application code would be something like Listing 5-4.
namespace TestProject
{
  internal class Program
  {
    static void Main(string[] args)
    {
    } // End of Main() method
  } // End of Program class
} // End of TestProject namespace
Listing 5-4

A “traditional” code example

In .NET 6 the console application template code will be like Listing 5-5.
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");
Listing 5-5

Code template in .NET 6

Remember we can switch off top-level statements when we create a new project, as in Figure 5-9.

A checkbox with the message, Do not use top-level statements is marked. Create button is framed on the lower right.

Figure 5-9

Switching off top-level statements

This new template code reflects new C# 10 features, which allow us to simplify our code. The two template codes, Listings 5-4 and 5-5, are effectively the same thing and will work in C# 10. C# 10 therefore allows us to

Write the code for the Main( ) method, leaving out the namespace, class, Main( ) method, and using statements.

This is very nice, when you know what you are doing and have a good understanding of the core C# programming fundamentals. For now, and throughout the chapters in this book, we will overwrite the code in the new template and work with the “older” format, where we will code the namespace name and the class name, include the Main() method when required, and display all the using statements. If we switch off the top-level statements by ticking the checkbox once on any project creation, the option will be remembered for future projects. All of this will become abundantly clear when we code the examples. By using our format in the chapter examples, it will allow us to understand C# code much better and be able to read code already written in this format, and we can then start using the “shortcut” style for future applications.

We will now copy the code from the Chapter4 Program.cs file and paste it into the Chapter5 Program.cs file.
  1. 1.

    Double-click the Program.cs file in the Chapter5 folder.

     
  2. 2.

    Delete the two lines of code in the Program.cs file.

     
  3. 3.

    Double-click the Program.cs file in the Chapter4 project.

     
  4. 4.

    Highlight all of the code.

     
  5. 5.

    Choose Copy from the Edit menu.

     
  6. 6.

    Double-click the Program.cs file in the Chapter 5 folder.

     
  7. 7.

    Paste the code copied from the Chapter 4 file.

     
  8. 8.

    Amend the code to change the namespace to Chapter5, as in Listing 5-6.

     
namespace Chapter5
{
  public class Program
  {
    public static void Main(string[] args)
    {
      Console.WriteLine();
      Console.WriteLine("------- Build your C# skills -------");
      Console.WriteLine("------- Learn To Code With C# -------");
      Console.WriteLine();
      Console.WriteLine("Press any keyboard letter to continue");
      Console.ReadLine();
      Console.WriteLine("Goodbye");
      Console.ReadLine();
    } // End of Main() method
  } // End of Program class
} // End of Chapter5 namespace
Listing 5-6

Namespace changed

We will now amend the code to include comments to demonstrate the use of single-line comments before a line of code and at the end of a code line.
  1. 9.

    Add comments to the program code, as in Listing 5-7.

     
// Program:    A simple C# program to output text and read input
// Author:    Gerry Byrne
// Date of creation:    01/06/2021
namespace Chapter5
{
  // This is our only class and it will contain the Main method
  public class Program
  {
    public static void Main(string[] args)
    {
      Console.WriteLine();
      Console.WriteLine("------- Build your C# skills -------");
      Console.WriteLine("------- Learn To Code With C# -------");
      Console.WriteLine();
      Console.WriteLine("Press any keyboard letter to continue");
      Console.ReadLine();// This line waits for the user to input
      Console.WriteLine("Goodbye");
      Console.ReadLine();
    } // End of Main() method
  } // End of Program class
} // End of Chapter5 namespace
Listing 5-7

Single-line comments

  1. 10.

    Right-click the Chapter5 project in the Solution Explorer panel.

     
  2. 11.

    Choose Set as Startup Project.

     
  3. 12.

    Click the File menu.

     
  4. 13.

    Choose Save All.

     
  5. 14.

    Click the Debug menu.

     
  6. 15.

    Choose Start Without Debugging.

     
The console window will appear as shown in Figure 5-10 and ask us to press any letter on the keyboard.

A Console window is displayed with three lines on it. The last line prompts the user to press any keyboard letter to continue.

Figure 5-10

Console output – waiting on keyboard input

  1. 16.

    Press any letter on the keyboard to continue, for example, a.

     
  2. 17.

    Press the Enter key.

     
The Goodbye message is displayed as shown in Figure 5-11.

A Console window prompts the user to press any keyboard letter to continue. On the next line, the user enters the letter a, the message Goodbye is displayed on the last line.

Figure 5-11

Console output

  1. 18.

    Press the Enter key.

     
  2. 19.

    Press the Enter key.

     

The code has produced an application that performs exactly as it did before we added the comment lines. So comments are for a reader of the code and do not change what the application does. The comments are ignored in the process of building and compiling the program from the source code we have written.

C# Multiple-Line Comments

Multiple-line comments , also called comment blocks, are enclosed between the symbols /* and */ and are used for longer comments. The /* is the start and the */ is the end of the block comment, as in Listing 5-8. We can also enclose a single-line comment between /* and */ symbols and it is still a valid comment.
/*
Longer comments in a C# program can easily extend over several lines so long as they start with the proper characters. This is an example of multiple line comments
*/
Listing 5-8

Multiple-line comment

We will now add a multiple-line comment that will help explain what a C# namespace is used for and another to say a little about the Main() method . As stated earlier, throughout the chapters we will use comments, and it is important to read them as they act as reinforcement of our knowledge or as an explanation.
  1. 1.

    Add the multiple-line comments, as in Listing 5-9, to our program code .

     
// Program: A simple C# program to output text and read input
// Author:  Gerry Byrne
// Date of creation: 01/06/2021
/*
C# programming namespaces are commonly used in two ways:
1. C#, or more precisely .NET, uses namespaces to organise the
many classes it contains (remember classes contain methods and
variables)
2. C# allows us as developers to create our own namespaces.
We can use the namespace keyword to declare a namespace
e.g. namespace Chapter5
A namespace can have the same name as the project but it can
also be any name we wish. The name is independent of the
Project name
*/
namespace Chapter5
{
  // This is our only class and it will contain the Main method
  public class Program
  {
    /*
    We now have our main method which will contain all our code.
    As we become a better developer, we will not have all our
    code contained within the main method.
    This would be seen as poor code and not fitting in with the
    design principle of modular code.
    */
    public static void Main(string[] args)
    {
Listing 5-9

Multiple-line comments

  1. 2.

    Click the File menu.

     
  2. 3.

    Choose Save All.

     
  3. 4.

    Click the Debug menu.

     
  4. 5.

    Choose Start Debugging.

     
The console window will appear and ask us to press any letter on the keyboard.
  1. 6.

    Press any letter on the keyboard to continue, for example, a.

     
  2. 7.

    Press the Enter key.

     
The Goodbye message is displayed as shown in Figure 5-12.

A Console window prompts the user to press any keyboard letter to continue. Letter a is entered on the next line, and the message Goodbye is displayed on the last line.

Figure 5-12

Console output

  1. 8.

    Press the Enter key.

     
  2. 9.

    Press the Enter key.

     

Chapter Summary

In this chapter we have added comments to our code to help us understand what the code is doing and to reinforce certain aspects of the C# programming language. We have used comments to give information about namespaces and the Main() method. Remember the golden rule: only use comments when they are required and the code itself is not self-documenting.

The code for the names of
  • The namespace

  • The project

  • The class

  • The variables

  • The constants

should be self-documenting, which means that no comments should be necessary for them. Some people would say

If we cannot write legible code, then it is unlikely we will be able to write legible comments.

Harsh? Maybe, but it reinforces the point that comments should not be a replacement for self-documenting code.

In finishing this chapter and increasing our knowledge, we are advancing to our target and making good progress.

An illustration of two-colored concentric circles with a text below that reads, our target is getting closer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.196.27