How to read user inputs from a console

A beginner guide to programming with .NET 5 and C#

Posted by Carl-Hugo Marcotte on March 14, 2021
How to read user inputs from a console
Photo by Jefferson Santos on Unsplash

In this article, we explore how to read user inputs from the console. This article is the foundation of more dynamic notions enabling our programs to change based on user interactions and react to them. We also learn how to change the title of the console and how to delete its content.

This article is part of a learn programming series where you need no prior knowledge of programming. If you want to learn how to program and want to learn it using .NET/C#, this is the right place. I suggest reading the whole series in order, starting with Creating your first .NET/C# program, but that’s not mandatory.

User input

So far, we used the Console.Write and Console.WriteLine methods to write to the console. We also created variables and constants to hold and reuse some text. However, we don’t know how to interact with the user yet.

There are multiple types of applications, like web apps, mobile apps, and Windows apps. In our case, we will continue to use console applications because they are the simplest. We don’t need to bother with complex user interfaces, animation, or interaction, and we can focus on learning to program.

Console apps may feel less exciting, but that allows us to focus on only one subject at a time. Remember that every piece of knowledge that you are acquiring is like a new LEGO® block that you’ll be able to piece with the others later. Moreover, what you are learning in this series is reusable in most, if not all, other types of apps.

The Console class offers three methods to read user inputs, Read, ReadKey, and ReadLine. We can use the first two for more complex scenarios. The third one is very straightforward and is the method we are focusing on in this article.

As its name implies, Console.ReadLine reads the line entered by the user. It is simple and gives us the power to accomplish what we need, to learn the basic programming concepts.

Reading a line entered by a user

The Console.ReadLine method returns a string, representing the line written in the console by the user. Here is an example:

using System;

Console.Write("Please enter a greeting message, then press ENTER: ");
var hello = Console.ReadLine();
Console.WriteLine(hello);

In the preceding code, we write a message to the user, then wait for an input. The program will block its execution there until the user hits the <ENTER> key. At this point, it will resume and continue, then write the read line back to the console.

Here is the console content when running the program and entering Hello Amigo!<ENTER>:

Please enter a greeting message, then press ENTER: Hello Amigo!
Hello Amigo!

More info: it is important to note that the new line character (the <ENTER>) is not part of the line (not saved in the hello variable).

Now that we saw an example, let’s explore the flow of execution of the program.

Flow of execution

The program flow, or flow of execution, represents the order in which the program executes the instructions (lines of code). In our case, the code is linear; it starts at the top and ends at the bottom of the Program.cs file. Nevertheless, the Console.ReadLine() method blocks the program, waiting for a user input, which disturbs the flow.

Here is what happens:

Code sequence

  1. The program writes the question to the console.
  2. The program executes the right-end of the assignation operator (=), the Console.ReadLine() method, which waits for the user to hit the <ENTER> key.

    More info: The assignation operator = is always the last to be executed; it has the lowest priority.

  3. The user types Hello Amigo! then hit <ENTER>.
  4. The program then resumes and assigns the user-entered value to the hello variable.
  5. The program writes that input back to the console.

Here is a second way to visualize this flow:

Code sequence graph

In this case, the Console.ReadLine() method manages the bifurcation even if code-wise, the flow is linear.

Note: We will learn ways to control a program’s flow in future articles.

Next, it is your turn to try this out.

Exercise

To practice all that we explored so far, including user-inputs, you must write a program that asks the following two questions to the user:

  1. What is your first name?
  2. What is your last name?

Then, the program must greet that user using the following format: Greetings {first name} {last name}!.

Example: Assuming the user entered Carl-Hugo as the first name and Marcotte as the last name, the greeting message would read Greetings Carl-Hugo Marcotte!.

Here are a few optional hints if you feel stuck:

Hint 1

Ask the first question, read the input, then repeat the same process for the second question.

Hint 2

Create two variables, one for the first name and one for the last name.

Hint 3

Use primarily Console.Write to write the text to the console.

Once you are done, you can compare with My Solution below.

My Solution

Program.cs

using System;

Console.Write("What is your first name? ");
var firstName = Console.ReadLine();

Console.Write("What is your last name? ");
var lastName = Console.ReadLine();

Console.Write("Greetings ");
Console.Write(firstName);
Console.Write(" ");
Console.Write(lastName);
Console.WriteLine("!");

Don’t worry if your solution is different than mine. As long as you completed it, it means you understood the lesson or at least practiced. Practicing is the key to success!

Good job! You completed another small chapter of your programming journey.

Bonus information

In this short section, we explore two more manipulations of the console:

  • How to set its title.
  • How to clear what is written in it.

Setting a custom console title

If you want to change the console title, you can set the Console.Title property to the string of your choice, like this:

Console.Title = "IntroToDotNet";

Pretty straightforward, isn’t it? Next, let’s see how to clear the text from the console.

Clearing the console

One last bit of knowledge here: we can clear the console using the Console.Clear() method. So instead of the following output:

What is your first name? Carl-Hugo
What is your last name? Marcotte
Greetings Carl-Hugo Marcotte!

We could clear the console between each question to obtain the following flow:

Adding Console.Clear calls

Here is the code to achieve that result:

Console.Clear Solution

Program.cs

using System;

Console.Title = "IntroToDotNet"; // Custom title

Console.Write("What is your first name? ");
var firstName = Console.ReadLine();
Console.Clear(); // Clear after the first question

Console.Write("What is your last name? ");
var lastName = Console.ReadLine();
Console.Clear(); // Clear after the second question

Console.Write("Greetings ");
Console.Write(firstName);
Console.Write(" ");
Console.Write(lastName);
Console.WriteLine("!");

And that’s it for this article.

Conclusion

In this article, we explored how to read user inputs from the console. We used the ReadLine method to acquire the value a user wrote before hitting the <ENTER> key. Interacting with the user is the foundation of the next many articles where we will use this to acquire and manipulate data typed by the user.

We also looked at how to change the title of the terminal Window because why not, right? Finally, we explored how to clear the text to reset the console to an empty state. This second interlude can be very handy at crafting a better user experience (UX).

Next step

It is now time to move to the next article: Introduction to string concatenation.

Table of content

Now that you are done with this article, please look at the series’ content.

Articles in this series
Creating your first .NET/C# program
In this article, we are creating a small console application using the .NET CLI to get started with .NET 5+ and C#.
Introduction to C# variables
In this article, we explore variables. What they are, how to create them, and how to use them. Variables are essential elements of a program, making it dynamic.
Introduction to C# constants
In this article, we explore constants. A constant is a special kind of variable.
Introduction to C# comments
In this article, we explore single-line and multiline comments.
How to read user inputs from a console You are here
In this article, we explore how to retrieve simple user inputs from the console. This will help us make our programs more dynamic by interacting with the user.
Introduction to string concatenation
In this article, we dig deeper into strings and explore string concatenation.
Introduction to string interpolation
In this article, we explore string interpolation as another way to compose a string.
Escaping characters in C# strings
In this article, we explore how to escape characters like quotes and how to write special character like tabs and new lines.
Introduction to Boolean algebra and logical operators
This article introduces the mathematical branch of algebra that evaluates the value of a condition to true or false.
Using if-else selection statements to write conditional code blocks
In this article, we explore how to write conditional code using Boolean algebra.
Using the switch selection statement to simplify conditional statements blocks
In this article, we explore how to simplify certain conditional blocks by introducing the switch statement.
Boolean algebra laws
This article explores multiple Boolean algebra laws in a programmer-oriented way, leaving the mathematic notation aside.
More to come Most likely in Q1 of 2022





Comments