Interacting via the Command-Line
Besides command-line input, another way to provide input to a program is via the Console. Typically, it works like this: You prompt the user for some input, they type something in and press the Enter key, and you read their input and take some action. Listing 1-3 shows how to obtain interactive input from the user.Listing 1-3. Getting Interactive Input: InteractiveWelcome.cs
- // Namespace Declarationusing System; // Program start classclass InteractiveWelcome { // Main begins program execution. public static void Main() { // Write to console/get input Console.Write("What is your name?: "); Console.Write("Hello, {0}! ", Console.ReadLine()); Console.WriteLine("Welcome to the Mahe's Home page!"); } }
There are three statements inside of Main and the first two are different from the third. They are Console.Write(...) instead of Console.WriteLine(...). The difference is that theConsole.Write(...) statement writes to the console and stops on the same line, but the Console.WriteLine(...) goes to the next line after writing to the console.
The first statement simply writes "What is your name?: " to the console.
The second statement doesn't write anything until its arguments are properly evaluated. The first argument after the formatted string is Console.ReadLine(). This causes the program to wait for user input at the console. After the user types input, their name in this case, they must press the Enter key. The return value from this method replaces the "{0}" parameter of the formatted string and is written to the console. This line could have also been written like this:
string name = Console.ReadLine();
Console.Write("Hello, {0}! ", name);
The last statement writes to the console as described earlier. Upon execution of the command-line with "InteractiveWelcome", the output will be as follows:
- >What is your Name?
[Enter Key] >Hello, ! Welcome to the C# Mahe !