ReadLine( ) and Input

In Chapter 3, you learned how to use WriteLine( ) to output messages to the console. Up until now, though, we haven’t shown you how to get any input from your users. The looping statements that we’ll introduce in the next section often go well with user input, so we’ll cover that now. C# has a ReadLine( ) statement that corresponds to WriteLine( ), and as you might guess, it reads in a string from the console into a string variable. The use of ReadLine( ) is rather simple. To take input from the console and assign it to the string inputString, you’d do this:

string inputString;
inputString = Console.ReadLine( );

Whatever the user types at the console, until he presses Enter—in other words, one line—is assigned to inputString.

It usually helps to give the user a prompt to let him know what he should be entering at a ReadLine( ), so it makes sense to start with a WriteLine( ):

Console.WriteLine("Enter your input string.")
inputString = Console.ReadLine( );

Often, though, you’ll want the user to enter his input on the same line, immediately after the prompt. In that case, you can use Write( ) instead of WriteLine( ). Write( ) outputs text to the console, the same as WriteLine( ), but it doesn’t send a newline character. In other words, if you follow a Write( ) with a ReadLine( ), the cursor waits at the end of the output for the user’s input:

Console.Write("Enter your name here: ");
string userName = Console.ReadLine( );

You’ll notice that ReadLine( ) accepts only a ...

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.