Console.ReadLine. This method reads input from the console—when the user presses enter, it returns a string. We can process this string like any other in a C# program.
C# programs will often use the Console.ReadLine method in a loop. With ReadLine() method calls we can repeatedly prompt for input.
Example. When developing programs, we will often want to loop through user inputs. This example uses a while-true loop and the Console.ReadLine() method.
Part 1 With a while-true loop the code loops infinitely. The loop will only exit with a special "exit" command.
using System;
class Program
{
static void Main()
{
// Part 1: loop indefinitely.
while (true)
{
// Part 2: get user input with a prompt.
Console.WriteLine("Enter input:");
string line = Console.ReadLine();
// Part 3: check string and report output.
if (line == "exit")
{
break;
}
Console.Write("You typed ");
Console.Write(line.Length);
Console.WriteLine(" character(s)");
}
}
}Enter input:
Dot
You typed 3 character(s)
Enter input:
Net Perls
You typed 9 character(s)
Enter input:
Integer input. Here we use the string from Console.ReadLine as an integer value. We can invoke the int.TryParse method to see if the result string is an integer representation.
Step 1 The line variable is assigned to the reference of the string data allocated by Console.ReadLine and filled with the input.
Step 2 The int.TryParse static method tests for a numeric value, and if this test succeeds we can then use the integer.
Step 3 This program tries to multiply an integer value received by the user by 10 and display the product.
using System;
class Program
{
static void Main()
{
// Step 1: read string from console.
Console.WriteLine("Type an integer:");
string line = Console.ReadLine();
// Step 2: try to parse the string as an integer.
int value;
if (int.TryParse(line, out value))
{
// Step 3: multiply the integer and display it.
Console.Write("Multiply integer by 10: ");
Console.WriteLine(value * 10);
}
else
{
Console.WriteLine("Not an integer!");
}
}
}Type an integer:
4356
Multiply integer by 10: 43560
Note, finally. We can insert a Console.ReadLine method call at the end of the Main method—or even in a finally block in the Main method. This will keep the terminal window open.
Summary. With the Console.ReadLine method, part of the System namespace, we can get a string from the console window. We can use the string to control a loop or exit the program.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Feb 13, 2025 (rewrite).