C# Console.ReadLine Example (While Loop)Use the Console.ReadLine method to read in user input as strings.
This 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.
When developing programs you will often want to loop through user inputs. This example shows how to use a "while (true)" loop and the Console.ReadLine method to do this.
Next: The example shows how to test the string value of the result. It shows how to access the Length property of that string.String Length
Main: Here the code loops infinitely while prompting the user in each iteration.
And: The program shows the length for each string typed. If the user types "exit", then the program immediately terminates.
C# program that uses Console.ReadLine loop
static void Main()
while (true) // Loop indefinitely
Console.WriteLine("Enter input:"); // Prompt
string line = Console.ReadLine(); // Get string from user
if (line == "exit") // Check string
Console.Write("You typed "); // Report output
You typed 3 character(s)
You typed 9 character(s)
Here we use the string from Console.ReadLine as an integer value. You can invoke the int.TryParse method to see if the result string is an integer representation.
Next: This program tries to multiply an integer value received by the user by 10 and display the product.
Line: The string "line" is assigned to the reference of the string data allocated by Console.ReadLine and filled with the input.
Then: The int.TryParse static method tests for a numeric value, and if this test succeeds we can then use the integer.ParseStatic
C# program that parses Console input
static void Main()
Console.WriteLine("Type an integer:");
string line = Console.ReadLine(); // Read string from console
if (int.TryParse(line, out value)) // Try to parse the string as an integer
Console.Write("Multiply integer by 10: ");
Console.WriteLine(value * 10); // Multiply the integer and display it
Console.WriteLine("Not an integer!");
Type an integer:
Multiply integer by 10: 43560
You can insert a Console.ReadLine method call at the end of the Main method—or even in a finally block in the Main method.
And: This will ensure the terminal window is never dismissed by Windows immediately on program completion.Finally
A summary. We looked at the Console.ReadLine method, part of the System namespace. We used it to accept input in a loop and testing the result each time.
we parsed the result of Console.ReadLine into an integer type for numerical processing. The Console.ReadLine method is useful in many console programs and is fairly simple to use.Console.WriteLine
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.