Write to and Read from the Console
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. |
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
The WriteLine() method to display data on the console
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;.
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.
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
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.
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
Let’s code some C# and build our programming muscle.
- 1.
Open Visual Studio.
- 2.
At the launch screen, choose Create a new project, as in Figure 4-5.
- 3.
Choose C# as the programming language from the drop-down list, as shown on the left-hand side of Figure 4-6.
- 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.
- 7.
In the Project name area, type the name of the project – ConsoleV1.
- 8.
Select the storage location for the project by using the … browse icon.
- 9.
In the Solution box, leave it as Create new solution.
- 10.
In the Solution name text box, type the name of the solution – CoreCSharp.
- 11.
Click the Next button.
- 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.
- 13.
Click the Create button.
The structure of the solution will be like that shown in Figure 4-10.
- 14.
Double-click the Program.cs file in the Solution Explorer window.
- 15.
Amend the code as shown in 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.
“Traditional” code sample
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.
- 16.
Click the Debug menu.
- 17.
Choose Start Without Debugging.
- 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.
- 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.
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.
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.
- 20.
Amend the code, as in Listing 4-5, to add a statement that requests the user to press a key on the keyboard.
WriteLine() to ask to press a keyboard key
- 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.
WriteLine() to display a message and ReadLine() to read a key
- 22.
Click the File menu.
- 23.
Choose Save All.
- 24.
Click the Debug menu.
- 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.
- 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.
- 27.
Press the Enter key on the keyboard.
- 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
- 1.
Click the Debug menu.
- 2.
Choose Start Without Debugging.
- 3.
Click the icon in the top left of the console window.
- 4.
Choose Properties from the drop-down list, as shown in Figure 4-16.
- 7.
Click the Screen Background radio button, as shown in Figure 4-18.
- 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.
- 9.
Click the OK button.
- 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.
- 11.
Press the Enter key.
- 12.
Press the Enter key.
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.
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.
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.
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.