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.
When developing programs, we will often want to loop through user inputs. This example uses a while-true
loop and the Console.ReadLine()
method.
while-true
loop the code loops infinitely. The loop will only exit with a special "exit" command.Console.ReadLine
.string
returned, and if it equals "exit," the program terminates. We show the length for each string
typed.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:
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.
string
data allocated by Console.ReadLine
and filled with the input.int.TryParse
static
method tests for a numeric value, and if this test succeeds we can then use the integer.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
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.
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.