© 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_4

4. Input and Output

Gerard Byrne1  
(1)
Belfast, Ireland
 

Write to and Read from the Console

We learned in Chapter 3 that under the direction of a program, written in a programming language and converted to machine-readable code, the computer can perform the following tasks , as shown in Table 4-1.
Table 4-1

Input, output, and process

Input

The computer can accept user input from the keyboard.

Process

The computer can perform arithmetic calculations and other types of processing.

Output

The computer can display a message or a result on the screen.

This chapter will concentrate on how to output to the console. We will also use a basic .NET method to read from the console, which is an example of input. It is very important to understand that what we learn by completing the examples in this chapter will
  • Help us build more complex code examples in future chapters

  • Show us commands that are used in real-world applications

  • Get us started with two important aspects of any programming language input and output

Looking back at Figure 3-2 from Chapter 3, we can think of the console as a black and white screen where input from the user is accepted and output from the computer program is displayed. The console colors can be changed as we can see from the lower part of Figure 4-1.

A console window contains the text Microsoft Visual Studio Debug Console, hello comma world exclamation mark in two color schemes.

Figure 4-1

Console in black and white and alternative color

So our console will display data, and in the C# programming language, we could achieve this with the line of code shown in Listing 4-1.
Console.WriteLine();
Listing 4-1

The WriteLine() method to display data on the console

Code Analysis
  • Fact 1

    First, we can see the keyword Console, so we might imagine this means something that interacts with the console, yes, the “screen,” where input from the user is accepted and output from the computer program is displayed.

  • Fact 2

    The second part is the full stop or period as it is also known. In programming languages like C#, the full stop means that we want to use a part or element of the object that appears to the left of the full stop, in this case Console. The object will generally be a class, and we talked a little about classes in the previous chapter, but we will also read a whole chapter on classes and objects. Now, let's look back to what we learned in the previous chapter:

    As we go through the course chapters, we will be reminded of the fact that a class contains methods and variables . This is a key concept and will be relevant when programming all the code examples.

    So, if Console is a class, it can contain methods and variables. When we add the full stop after the class name, we are saying we want to use either a method or a variable that is inside the class. Remember () indicates a method. It was also said in the previous chapter:

    Likewise, we can create namespaces to hold our classes, and we can use the namespaces created by Microsoft in our code to get access to the Microsoft base classes .

    Microsoft base classes will be like the classes we write; they contain methods and variables, which we can use without having to write them. Console is one such base class and it therefore contains methods and variables that we can use.

  • Fact 3

    The third part is WriteLine().

    Let’s look back to what we learned in the previous chapter:

    So () means a method.

    We should now be able to recognize that WriteLine() is indeed a method, and as it has nothing between the brackets (), we should understand that this means the method accepts no value or values. We will see in Chapter 12 on methods that it is a parameterless method; it accepts no parameters, values.

  • Fact 4

    Console belongs to a namespace called System. This is not obvious from the line of code, but it will become obvious as we start to write the code in our Integrated Development Environment (IDE). To explain this, we can think back to what we learned in the previous chapter:

    The lines of code at the start of the program code usually have a format that starts with the keyword using.

The word using refers to the fact that we wish to use classes, and ultimately the methods and variables in the classes, that are contained in the namespace that follows it, for example, using System;.

So we can see a namespace called System being used in our C# code and this illustrates another important concept to get used to when programming :

We will use classes that already exist to help us build our own applications using C# code.

Always remember the key fact that a class contains methods and variables , so when we tell our code to use an existing class, which exists in a namespace, we are doing this to get access to methods and variables that already exist and will help us in building our application with C# code.

When we use an Integrated Development Environment like Microsoft Visual Studio, we will receive assistance when we type a class name followed by the dot or period. We call this dot notation , and it presents us with a list of methods and variables that exist in the class, very handy for us as developers. Figure 4-2 shows an example of what Visual Studio presents developers when the dot is entered after the keyword Console. We see the variables, also referred to as fields, members, or properties, and the methods that exist in the Console class.

A context menu of the Console class. The write line option is highlighted.

Figure 4-2

Dot notation showing methods and properties of the Console class

If we study the icons, this will help when we are coding our applications. There are three different icons representing three aspects of the class. For now, let's just get familiar with two of the icons that represent the variables and the methods:

The spanner

The spanner represents a property of the class. Let’s look back to what we learned in the previous chapter:

We will also see later that, instead of saying variable, we will say property or field or member when we talk about them in classes.

So we use the word property when we are inside a class, but we may also see it called a member. Clicking the spanner icon at the bottom of the pop-up window will display only the properties of the class, as shown on the left-hand side in Figure 4-3.

Two context menus of the dot notation properties. Background color and write line options are highlighted.

Figure 4-3

Dot notation showing properties on the left and methods on the right

The cube

The cubes , as shown on the right-hand side in Figure 4-3, represent the methods of the class. A method is a block of code.

The “lightning bolt” symbol

The “lightning bolt,” as shown in Figure 4-4, represents an event handler . This is more related to actions from controls on a form, like clicking a button. Later in the book, we will study events within a console application, but events for form-based applications are not part of our book. We will be concentrating on console applications rather than form- or web-based applications. However, as we have read previously, once we get the core programming skills, the fundamentals, it will be possible to apply these to form- and web-based applications where events like clicking a button will be commonplace. Such programming can also be classified as event-driven programming.

A window of the dot notation. The option Cancel Key Press and a lightning bolt icon are highlighted.

Figure 4-4

Dot notation showing event handlers only

Let’s code some C# and build our programming muscle.

Now it is time for us to do some C# coding. The C# console application we will code will use the Console.WriteLine() method to output data to the console window and then use the Console.ReadLine() method to read the keyboard input and effectively end the program.
  1. 1.

    Open Visual Studio.

     
  2. 2.

    At the launch screen, choose Create a new project, as in Figure 4-5.

     

A window for project creation. 4 options under Get started, clone repository, open a project or solution, open a local folder, and create a new project are highlighted.

Figure 4-5

Create a new project

  1. 3.

    Choose C# as the programming language from the drop-down list, as shown on the left-hand side of Figure 4-6.

     

A window for program language selection. C, hash sign option, and Console are highlighted under the dropdown menu list.

Figure 4-6

Select the language as C#

  1. 4.

    Choose Console in the project type section, as shown on the right-hand side of Figure 4-6.

     
  2. 5.

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

     

A window of the Console app interface. C hash sign, Linux, mac O S, Windows, and Console tabs are observed.

Figure 4-7

Console App

  1. 6.

    Click the Next button.

    All our code can be saved in one location called a solution. The solution is really a folder on our computer. Once we create the solution, we will create projects within it, and these projects are really folders within the solution. So now we need to create a solution on our computer as we create this project. The location is a matter of choice; we decide where to locate the solution folder and the project folder. Figure 4-8 shows an example.

     
  2. 7.

    In the Project name area, type the name of the project ConsoleV1.

     
  3. 8.

    Select the storage location for the project by using the … browse icon.

     
  4. 9.

    In the Solution box, leave it as Create new solution.

     
  5. 10.

    In the Solution name text box, type the name of the solution CoreCSharp.

     

A window for the Console app has 4 text input fields labeled Project name, Location, Solution, and Solution name. All the fields are filled out.

Figure 4-8

Solution and project details

  1. 11.

    Click the Next button.

     
  2. 12.

    Choose the framework to be used, which in our projects will be .NET 6.0 or higher, as shown in Figure 4-9. Remember to switch off top-level statements.

     

A window of the interface of the Console app. The option, Do not use top-level statements is checked, a 2-line U R L is crossed out, and the create button below is highlighted.

Figure 4-9

Choose the framework version

  1. 13.

    Click the Create button.

    The structure of the solution will be like that shown in Figure 4-10.

     

A solution explorer panel window. The solution name, console project, and main console program are exhibited.

Figure 4-10

Solution Explorer panel

  1. 14.

    Double-click the Program.cs file in the Solution Explorer window.

     
  2. 15.

    Amend the code as shown in Listing 4-2.

     
using System;
namespace ConsoleV1
{
   internal class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine();
      Console.WriteLine("------- Build your C# skills -------");
      Console.WriteLine("------- Learn To Code With C# -------");
      Console.WriteLine();
      Console.ReadLine();
    } // End of Main() method
  } // End of Program class
} // End of ConsoleV1 namespace
Listing 4-2

ConsoleV1 code

Sometimes we will be given a template with some code existing within it, or we might copy code from a source such as the Internet, and we will have using statements at the top. When this happens, we need to be sure we will need all the using statements.

We will see from Figure 4-11 that some of the using statements look different from those we typed in our code. We will see that those we did not enter in our code are being “flagged” by our Integrated Development Environment; the lines have gray text. This indicates that they are not being used in our code, and hovering over one of the unnecessary lines of code produces a pop-up message as shown in the Figure 4-11. Removing unused code is a basic principle for writing what is termed “clean code.” We will now look at some ways in which we could “tidy” our code by removing using directives that are unnecessary.

A window labeled Console V 1. A text labeled unused using directives points to a 12-liner code with a superimposed prompt window.

Figure 4-11

Unused code – unused using statements

A window before and after choosing the remove and sort usings option. The Remove and sort usings option in the context menu in the before window points to a line code labeled using System and the window for after displays an 11-line code.

Figure 4-12

Context menu with the Remove and Sort Usings option

We saw in the last chapter that the code as shown in Listing 4-3 could be shortened using top-level statements to the code shown in Listing 4-4.
using System;
namespace ConsoleVersion1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Console.ReadLine();
        } // End of Main() method
    } // End of Program class
} // End of ConsoleVersion1 namespace
Listing 4-3

“Traditional” code sample

      Console.ReadLine();
Listing 4-4

Code when we use top-level statements

So how can this be? Well, .NET version 6.0 and C# 10 introduced the concept of implicit using directives, which means the C# compiler will automatically add a set of using directives based on our project type. For console applications, which we will be using, the directives that are implicitly included are

using System;

using System.IO;

using System.Collections.Generic;

using System.Linq;

using System.Net.Http;

using System.Threading;

using System.Threading.Tasks;

Therefore, this is why we do not have to include the using System; statement at the top of our code.

C# 10 also introduced the concept of a global using directive, which means we do not have to write the same using directives in each file in our project. It is now possible to convert an ordinary using directive into a global using directive by adding the global modifier: global using System;. If we add this at the top of any file in our project, it will be as if we added it to all the files in the project.

Another way to manage the using directives is to use the context menu, which can be displayed by right-clicking in the code. There will then be an option to Remove and Sort Usings, as shown in Figure 4-12, and if this is selected, the unnecessary using directives will be removed, while all other required using directives will be sorted.

  1. 16.

    Click the Debug menu.

     
  2. 17.

    Choose Start Without Debugging.

     
  1. 18.

    Press the Enter key to continue the code execution as the code has paused on the Console.ReadLine() statement waiting for a key to be pressed on the keyboard, as shown in Figure 4-13.

     
  2. 19.

    Press the Enter key again to close the console window.

    The console window will disappear, and the application will be terminated as there are no lines of code to be executed after the Console.ReadLine() line.

    Code Analysis

    Console.WriteLine()
    • This means write a line to the console, and since there is no information between the brackets (), the line will be blank. With the WriteLine() command, the cursor will move to the next line as its final act.

     

A command window contains text that reads, Build your C hash sign skills and Learn to Code with C hash sign.

Figure 4-13

Console output in black and white

Console.WriteLine("------- Build your C# skills -------");
  • This means write a line to the console, and since there is information between the brackets (), the line displays the text exactly as shown between the double quotes “”. The double quotes indicate that the displayed text is always going to be whatever has been typed between the double quotes; it is a string. The text is therefore a constant; it will not change throughout the lifetime of the application. We could say it is not a variable, so it is a constant. With the WriteLine() command , the cursor will move to the next line as its final act.

Console.ReadLine()
This means read a line from the console. It is input.
  • Fact 1

    Here again, first, we can see the keyword Console and, as stated previously, this refers to something that interacts with the console. In this case we will use Console to interact with the console in Visual Studio, where input from the user will be accepted. This is different from the output from the computer program in Listing 4-2 when we used the Console.WriteLine() method.

  • Fact 2

    The second part is the dot, the full stop or period as it is also known. As we saw earlier, in C# code the full stop means that we want to use a part or element of the object that appears to the left of the full stop. The part or element will be a variable or a method.

  • Fact 3

    The third part is ReadLine().

    We should now be able to recognize that ReadLine() is indeed a method; it has the brackets () at the end. As this method has nothing between the brackets (), we should be aware that this means the method takes in no value. It is empty of input parameters.

  • Fact 4

    Console belongs to a namespace called System. As stated previously, this is not obvious from the line of code. If we really wanted to make this fact obvious, we could have written the line of code as System.Console.ReadLine();

    In our code we could

  • Use the full naming convention System.Console.ReadLine(); and NOT have the using System at the top of the code.

  • Use the shortened version Console.ReadLine(); and have the using System at the top of the code.

As developers it is our choice. The reality is that most developers in the technology world will probably use the shortened version. We will therefore see in nearly every commercial C# application code a lot of using statements at the top of the code, including using System , but we must remember that this directive is one of the directives that are implicitly included in a console application and it can therefore be omitted.
  1. 20.

    Amend the code, as in Listing 4-5, to add a statement that requests the user to press a key on the keyboard.

     
      Console.WriteLine("------- Learn To Code With C# -------");
      Console.WriteLine();
      Console.WriteLine("Press any keyboard letter to continue");
      Console.ReadLine();
    } // End of Main() method
  } // End of class
} // End of namespace
Listing 4-5

WriteLine() to ask to press a keyboard key

  1. 21.

    Amend the code, as in Listing 4-6, to display a message saying Goodbye to the user. Then, as we see the message, add another read line statement.

     
      Console.ReadLine();
      Console.WriteLine("Goodbye");
      Console.ReadLine();
    } // End of Main() method
  } // End of class
} // End of namespace
Listing 4-6

WriteLine() to display a message and ReadLine() to read a key

  1. 22.

    Click the File menu.

     
  2. 23.

    Choose Save All.

     
  3. 24.

    Click the Debug menu.

     
  4. 25.

    Choose Start Without Debugging.

    The console window will appear, as shown in Figure 4-14, with the message being displayed. The cursor will be flashing waiting for user input.

     

A command console window contains text that reads, Build your C hash sign skills and Learn to Code with C hash sign and Press any keyboard letter to continue.

Figure 4-14

Console waiting for a key press

  1. 26.

    Press any key on the keyboard.

    The Goodbye message will appear, as shown in Figure 4-15, and the cursor will be flashing waiting for user input.

     

A command console window contains text that reads, Build your C hash sign skills and Learn to Code with C hash sign, and Press any keyboard letter to continue and goodbye.

Figure 4-15

Console accepts a key and displays the message

  1. 27.

    Press the Enter key on the keyboard.

     
  2. 28.

    Press the Enter key again.

     

Now that we have the concept of input and output and we have started using lines of C# programming code that industry developers use, we can progress to using other programming concepts in our code.

Change Console Display Settings

When the console window is visible on the screen, we can amend the console window preferences , as shown in Figure 4-16.
  1. 1.

    Click the Debug menu.

     
  2. 2.

    Choose Start Without Debugging.

     
  3. 3.

    Click the icon in the top left of the console window.

     
  4. 4.

    Choose Properties from the drop-down list, as shown in Figure 4-16.

     

A command window context menu. The option Properties is highlighted.

Figure 4-16

Console display settings

  1. 5.

    Click the Screen Text radio button, as shown in Figure 4-17.

     
  2. 6.

    Change the values for the Red, Green, and Blue to be 0, as shown in Figure 4-17.

     

A console display settings window has 4 settings tabs. The colors tab for screen text is selected, and the color value options for red, green, and blue are highlighted.

Figure 4-17

Console display settings – text color

  1. 7.

    Click the Screen Background radio button, as shown in Figure 4-18.

     

A console window display settings. The colors tab for the screen background is selected, and the color value and screen color options are highlighted.

Figure 4-18

Console display settings – background color

  1. 8.

    Change the background color by picking from the row of displayed colors or entering values for the RGB colors, as shown in Figure 4-18.

     
  2. 9.

    Click the OK button.

     
  3. 10.

    Press the Enter key.

    The console window will be as shown in Figure 4-19, with the message being displayed. The cursor will be flashing and is waiting for user input.

     

A command console window contains text that reads, Build your C hash sign skills and Learn to Code with C hash sign, and Press any keyboard letter to continue and goodbye in a grey color scheme.

Figure 4-19

Console display settings have changed background and text

  1. 11.

    Press the Enter key.

     
  2. 12.

    Press the Enter key.

     
The following points are important in understanding this C# program and will be applicable to many of the programs we write in the future:
  • The using statements at the top of the code represent namespaces that contain classes that we need to help our program work.

  • Classes are program code that hold properties and methods that are made available to the programmer.

  • We are developing a C# project and the project has a Program.cs class.

  • It is in this Program class that we have written our code. In future projects we can rename the Program class or add a new class and give it a name of our choice.

  • This class has what is called an access modifier in front of the word class. The access modifier is the default access modifier of internal. Having the default take control is never a good idea or good practice. We could, and should, add an access modifier instead of the default to help make the code more readable and understandable. It is our program, so we need to control what is going on. If we add the word public in front of the word class, as in Listing 4-7, we are telling the class that it is accessible by other code in the project; this is a simplified definition but sufficient for us at the moment.

  • If we remove the keyword internal from in front of the word class, then the default will be used and the code will be the same whether or not the word internal is present.

namespace ConsoleV1
{
   public class Program
  {
    static void Main(string[] args)
    {
Listing 4-7

The public keyword in front of the class

  • The curly left brace on the line following internal class Program matches the closing brace on the second last line of the example, as in Listing 4-8, with the comment // End of class. This is because the whole class definition is between the open and close braces.

namespace ConsoleV1
{
  internal class Program
  {
    static void Main(string[] args)
    {
    } // End of Main() method
  } // End of class
} // End of namespace
Listing 4-8

The opening and closing curly braces to contain the code

  • The code in the class can be included within the method called Main().

    As we read the chapters in the book, we will often see that when a method is referred to by name, it will also include the open and close parentheses, (). This technique is used to emphasize and reinforce that () means a method, a block of code. The actual name of the method is the name without the (), for example, Main rather than Main().

  • The method also has what is called an access modifier in front of the words static void. The access modifier may not be visible because we did not type it, and so the default access modifier of private is invisibly added. We could add a different access modifier. We could add the word public in front of the word static, as in Listing 4-9, and therefore we are telling the Main() method that it is accessible by other code in our project. Remember the idea of default is not helping us fully understand the code we are reading or writing.

namespace ConsoleV1
{
  internal class Program
  {
    public static void Main(string[] args)
    {
    } // End of Main() method
  } // End of class
} // End of namespace
Listing 4-9

The public keyword in front of the Main() method

  • The method signature , Main(string[] args), defines the name of the method, Main, which is followed by the method body, which is enclosed in braces.

  • The words static and void will be explained later, but they are always used with a Main() method. The two words static and void are examples of C# keywords, words that have a special meaning in a C# program and that cannot be used for any other purpose.

  • The other keywords in the preceding example are public and class.

  • The Console.WriteLine() statement displays the text contained between the brackets () and inside the quotes in a console window.

  • The Console.ReadLine() statement waits to read a line of text from the console. The line of text is determined when the Enter key has been pressed.

  • These lines of code within the Main() method constitute C# statements, that is, commands to be carried out.

  • Each C# statement is terminated by a semicolon ;

Chapter Summary

In this chapter we have seen and applied the concept of input and output and we have started using lines of C# programming code that industry developers use. We started using the Integrated Development Environment, Visual Studio, to maintain a solution that contains our first C# project. We will be adding other projects to this solution, but we have made a great start in developing a solution with a project, which helps with the concept of separation of concern, which means each of our projects can work independently. Within our project we met the Program.cs class where we added our code. In typing our code, we met the method, represented as a cube; the property, represented as a spanner; and the event, represented as a lightning bolt. And we saw that colors within the code editor, like the symbols, helped make our code easier to code, read, and eventually maintain. Finally, we looked at how to change the console appearance from a black background to another color using the Properties option.

As we progress, we will be using other programming concepts in our code, but we have made great progress in learning the essentials for writing a C# application using an Integrated Development Environment like Visual Studio. We have used C# statements, and if we refer to the recipe in Table 3-1 in Chapter 3, we will see that statements are like the ingredients of the recipe.

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

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.137.151.61