Get User Input in C# with Console.ReadLine()

GET USER INPUT WITH CONSOLE.READLINE()

by

This tutorial will teach you how to take input from a user in C# using the Console.ReadLine() method. When writing a computer program, you will often rely on a user interacting with your program. For example, your program may ask the user a question, wait for a response, and then do something with the information the user provides. Creating these types of dynamic user interactions becomes increasingly important as we write more complex programs in C#.

That is precisely the type of program we will be writing in this example.

C# Console.ReadLine() Example

In this example, we will write a .NET Core console application that gathers information from an end user and then we will process that data and print some results to the screen. Start by creating a new Project (File > New > Project...) and select the .NET Core Console App template. You can call the project UserInteraction.

You will be shown a boilerplate template that you are, by now, familiar with. This example will incorporate several features from our previous tutorials. Recall in our first C# program, we called the Console.ReadLine() method to force our console application to wait for user input and prevent the terminal window from immediately closing after our code was executed. In this example, that same method will serve as the basis for our user interaction.

In the previous lesson, we learned about different data types and how to declare variables. In this example, we will be using variables of type Integer and String.

Let's get started by adding the following lines to your Main() method:

Console.WriteLine("What is your name?");
Console.Write("Type your first name: ");

You will notice in Line 10, we use Console.Write() instead of Console.WriteLine(). The difference between the two methods is that the .WriteLine() method of the Console class appends a new line character after the string, forcing the cursor to move to the next line. The Write() method, on the other hand, will print a string and leave the cursor at the end of the line, without moving to a new line.

Now we will declare a string variable and use it to capture the user's input. Add the highlighted lines to your code:

Console.WriteLine("Tell me about yourself.");
Console.Write("Type your first name: ");
 
string myFirstName;
myFirstName = Console.ReadLine();

In line 12, we declared a string variable called myFirstName. Then, in line 13, we used the assignment operator ( = ) to assign a value to that variable. We want myFirstName to have the value of whatever the user types in the console. When the user types his name and presses the Enter key, the name is saved to the variable myFirstName and can be used elsewhere in your program.

Let's get some more information from the user. Let's ask for the user's last name. What type of variable should we use?

Console.WriteLine("Tell me about yourself.");
Console.Write("Type your first name: ");
 
string myFirstName;
myFirstName = Console.ReadLine();
 
Console.Write("Type your last name: ");
string myLastName = Console.ReadLine();

We use another String variable to save the user's last name. Notice on Line 16, we declare a variable and assign a value all on one line. This is a shorter way to do what took us two lines in lines 12-13. It is good practice to assign a value to a variable as soon as possible after we declare it. Moreover, our code is shorter and easier to read when we organize it this way.

Getting an Integer from Console.ReadLine()

Next, let's ask the user for the year he/she was born. We will want to store that value in a new valuable, and make some calculations with it in order to determine the person's age. What variable data type do you think we should use?

Console.WriteLine("Tell me about yourself.");
Console.Write("Type your first name: ");
 
string myFirstName;
myFirstName = Console.ReadLine();
 
Console.Write("Type your last name: ");
string myLastName = Console.ReadLine();
 
Console.Write("What year were you born? ");
int myBirthYear = Convert.ToInt32(Console.ReadLine());

If we only wanted to show the value somewhere else in our application, we could just use a String like we did when we were taking the user's name. However, we will be performing mathematical calculations, and we can't do that on Strings. We need to store the value as some type of number. A birth year, like 1980, is a whole number value, so we can declare an Integer variable. I will use the tip we learned earlier to declare a variable and assign it a value on one line (Line 19).

Observe that we have added some special code, Convert.ToInt32(), in order to save the value of Console.ReadLine() to an Integer data type. Console.ReadLine() expects a sequence of alphanumeric Unicode characters, a String. We can't assign a String to an Integer variable. The data types don't match. We will use the ToInt32() method of the Convert class in order to parse our String as an Integer. With this method, we can convert an alphanumeric string into a whole number and be able to use it to make calculations in our program.

Note: In a real application, we would want to include some error checking to ensure that the value entered is actually a number before we try to convert it.

A Complete Console.ReadLine() Example

Until now, we have simply saved the user's input to a variable, but we haven't actually done anything with that data. To finish our program, we will want to present some content to the end user based on the data they have provided.

using System;
 
namespace UserInteraction
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Tell me about yourself.");
            Console.Write("Type your first name: ");
 
            string myFirstName;
            myFirstName = Console.ReadLine();
            
            Console.Write("Type your last name: ");
            string myLastName = Console.ReadLine();
 
            Console.Write("What year were you born? ");
            int myBirthYear = Convert.ToInt32(Console.ReadLine());
 
            Console.WriteLine();
            Console.WriteLine("Hello, " + myFirstName + " " + myLastName);
 
            int myAge = DateTime.Now.Year - myBirthYear;
            Console.WriteLine("This year, you will be " + myAge + " years old.");
 
            int newAge = myAge + 5;
            Console.WriteLine("In 5 years, you will have " + newAge + " years.");
            Console.ReadLine();
        }
    }
}

On Line 21, we are simply inserting a blank line into the console to provide some spacing between the questions we have asked and the output we are about to display. On Line 22, we are joining our strings together with the Concatenation Operation ( + ). Notice, we can write a string inside double quotes like we have been doing, but we can also reference our existing string variables by their name. Since these variables were assigned values based on the user's input, their first and last name will appear in our console application.

On Line 24, we calculate the user's age based on the year they were born. We do this by subtracting the user's birthyear, a value the user provided, from the current year which we retrieve using DateTime.Now.Year. There are a lot of interesting things we can do with a DateTime variable, so that will be a separate tutorial of its own! For now, it is sufficient to say that DateTime.Now fetches the current local date and time, and Year is a property of the DateTime structure that gets the year represented by our DateTime instance.

On Line 27, we make another calculation with an Integer variable. This time, we want to tell the user how old they will be in five years. We will use the age we just computed on Line 24, and simply add 5 to that value. Finally, we write this to the console and our application is complete. If you run your interactive program, you should see something like the following:

The Bottom Line

In this tutorial, we learned how we can use the Console.ReadLine() method to capture a user's input. We learned how to save those values as String variables in order to retrieve them later in our program. We learned that Console.ReadLine() returns a String, so if we want to save that String as a number, we have to make a conversion. Once we have the variable saved as an Integer data type, we can retrieve it to make calculations.

What useful ideas do you have for the Console.ReadLine() method? Let me know in the comments! As always, if you have any questions, let me know below.


Don't stop learning!

There is so much to discover about C#. That's why I am making my favorite tips and tricks available for free. Enter your email address below to become a better .NET developer.


Did you know?

Our beautiful, multi-column C# reference guides contain more than 150 tips and examples to make it even easier to write better code.

Get your cheat sheets