Most programs don't just run and perform a function without any type of user input. User input is any click command, text from a keyboard, or entry in a form. In almost any program, you need to handle user input. You work with user input in console applications, local desktop applications, or your website pages. This article focuses on user input, how you can handle different data types, and returning a response to the user.
Console Input
The simplest C# program is a console application. These applications use the Microsoft command line to display information and take user input from the keyboard. Most beginner programmers learn how to deal with user input using the console, because these applications are the easiest to set up and configure. We'll discuss input from web applications in later chapters.
C# requires two types of statements when you want to work with console input and output. The first statement is the output statement. This statement prompts the user for what must be entered. It also takes the calculated input and displays some information back to the user. For instance, you can create a simple calculator with a console application. You display a prompt asking the user to enter two numbers. The numbers are then added together and the result is displayed back to the user. Both the prompting statement and the resulting output are both a form of console output.
The second statement you need is the input statement. This statement stops execution of the application and waits for the user's input. The user could close the application, which stops execution as well, but you assume in your code that the user will send some data for you to process. If the user decides to close the program, it does not crash the machine. It can cause issues if you store the information in a database, but we'll assume that you're just asking for input, performing a calculation, and then displaying the output to the user.
Let's take a look at some code that handles user input. Since this is a console application, you need to fire up Visual Studio for Desktop.
using System;
namespace WhatsMyInfo
{
public class Program
{
public static void Main()
{
string name;
int age;
int birthyear;
Console.Write("Please enter your name: ");
name = Console.ReadLine();
Console.Write("Please enter your age: ");
age = Convert.ToInt32(Console.ReadLine());
Console.Write("What year were you born?: ");
birthyear = Convert.ToInt32(Console.ReadLine());
//Print a blank line
Console.WriteLine();
//Show the details that the user entered
Console.WriteLine("Name is {0}.", name);
Console.WriteLine("Age is {0}.", age);
Console.WriteLine("Birth year is {0}.", birthyear);
}
}
}
If you compile the above code, it will run through the program until the end of the Main function is found. Let's break down the code line by line.
using System;
Any using statements are always found at the top of a C# program file. The using statement lets you import namespace libraries. At the very least, you need the System namespace. The .NET framework is made up of dozens of namespaces and libraries. You won't remember them all, but you should be familiar with some of the popular ones. System imports the very basic functionality for a console application.
namespace WhatsMyInfo
This line gives our program a name. We only have one class included with this program, but you can have several classes contained within a namespace. This name can be imported in other namespaces if you needed to expand your program to other applications.
This namespace is also used to name the executable that you'll use to run your new program. This means that when you compile the application, the application is compiled into an executable file named WhatsMyInfo.exe.
public class Program
This is the opening of your program's class. Visual Studio defaults to the class name Program when you create a new project. You can rename this class if you want to create a real application, but this console program is just for demo purposes, so we left it with the default. All of your console code is located within this class.
public static void Main()
If you've ever worked with other C-style languages, you'll recognize this function. Remember that functions within a class are called methods, so technically this would be referred to as a method and not a function. C programs start with a function (or method in this case) named Main. The Main function is required by the compiler to identify the start of your program. You will have dozens of classes and functions, but the Main function is where the program execution always starts.
Notice that the Main function is set to public. This is necessary for the compiler to find the Main function. If it was set to private, not other classes or namespaces could access it. The Main function is also static, because it' doesn't need to be instantiated. We mentioned in Chapter 2 that static functions and variables can be accessed without instantiation. We'll discuss instantiation in later chapters. Just know that the public and static modifiers are standard for the Main function. The void designation is also standard.
string name;
int age;
int birthyear;
Just like any other program, we need variables to store values for our program. We want to ask the user for a name, age and birthyear. It's important that you give each variable the right data type. You could set all variables as strings, but this would make your program inefficient and poorly coded. User input is always a string, but you want to designate a data type that matches the data stored. We set age and birthyear as an integer even though the user input is initially set as a string.
Console.Write("Please enter your name: ");
Now, we get into the code that begins prompting the user for input. The "Console.Write" command is specific to C#. It writes output the user. Note that this does not stop execution. The next statement actually stops execution and waits for the user to enter input. The above statement just sends "Please enter your name" to the console and then the next statement executes.
name = Console.ReadLine();
This is the statement that stops execution and waits for user input. If you run your program with just the previous two statements, output is shown to the user and then execution stops waiting for the user to enter information. The console will read all data up until the enter key is pressed. The enter key sends a message to the program that the user has entered all data requested.
The Console.ReadLine function grabs the user information entered and then places the value in the name variable. Note that the user can enter anything. Since user input is automatically set as a string, numbers, special characters or any other input is accepted. It's up to the developer to perform validation checks. For instance, you could create code that loops through the string and identifies if any numeric values were given. You can assume that a numeric value in a name is incorrect, and then send a message to the user to re-enter information. For this demo, we will accept any input from the user.
Console.Write("Please enternter your age: ");
age = Convert.ToInt32(Console.ReadLine());
Console.Write("What year were you born?: ");
birthyear = Convert.ToInt32(Console.ReadLine());
The above code contains the other two variables and user input prompts. Each time the compiler reaches the ReadLine() function call, it stops and waits for user input.
Notice that we use the Convert class in these two input statements. We mentioned that all input from a user is in string format. You could create three variables that contain strings, but age and birthyear are integers. Using strings would be inefficient code. In addition, you will likely store these values in a database if this was a real-world application. For this reason, you want to create variable data types that represent the values stored in each variable.
Since the input from a user is a string, you need to convert the string to the correct data type. If you attempted to run this program without the Convert class actions, the program would fail and the compiler would give you an error. For this reason, you must convert the input to the proper data type before you store it to the variable. You could also create temporary variables and convert the string values in them, but this again would be inefficient code. The above code statements are how you properly retrieve input and then convert the values to the correct data type before storing them in their appropriate variables.
Both birthyear and age are set with the integer data type, so we must convert the input to this data type. The Convert.ToInt32 function converts any string value to an integer provided the actual input is indeed an integer. If you have any letters or special characters, the conversion will fail. This is again another example of a programmer's responsibility to check the validity of the input and return a prompt if the right input is not entered.
We assume that the input is only an integer just to keep the program simple. Error correction and validation of input is an important part of programming in any language, but it's a complex subject that makes it too difficult to learn a language. If you want to see what happens when you don't properly validate input, run the program and enter a string for integer input. The program will give you an error and crash, but it won't harm your program.
Returning to the topic of our code, the Convert.ToInt32 changes the string input to an integer so that the value can be stored in the age variable. We then send input again asking for the user's birth year. Again, execution stops and the program waits for user input. The user enters a birth year, the string input is converted to an integer using the Convert.ToInt32 static class function, and then the value is stored in the birthyear variable.
//Print a blank line
Console.WriteLine();
We added this line of code for aesthetics. This line of code just outputs a blank line in the program. It does nothing but separate the user input from the output that we're about to display. It's important to think about user experience when you create your programs. Always make input and output easy to understand for the user. When user experience is poor, users find other programs that are more easily understood. Usability should also be an issue when you code your program. We add a blank line to make it easy for the user to skim through the console output and identify the input and separate it from the output. Our program is small, but good formatting helps improve the usability of your program.
//Show the details that the user entered
Console.WriteLine("Name is {0}.", name);
Console.WriteLine("Age is {0}.", age);
Console.WriteLine("Birth year is {0}.", birthyear);
These three lines complete the output of your program. We simply repeat what the user input in three strings. All three statements use the WriteLine function to display information. This function automatically appends a carriage return to the end of the line. This means that each statement outputs information on its own line. The carriage return character is the character representation of what happens when you press the Enter key on your keyboard. The end of the line terminates and a new one is created. This is the purpose of the WriteLine function, so you don't need to manually code the carriage return. The carriage return character is represented as the symbol "\n" in most C-style languages including C#. You could use the Console.Write function with the new line character ( \n ) in your C# statements, and the result of the output would be the same. Remember that you want to keep your code clean and efficient, so the Console.WriteLine function is preferred over the alternative.
You'll notice that the string output is "Name is {0}" with a comma and the variable. The {0} instructs the program to use the first variable in the list. The first variable is identified and replaces the {0} notation with its value. Note that we don't need to convert the variable back to a string even though the output is a string statement. The C# language automatically converts the variable.
You can also have other variables in the list. They must be separated by a comma. For each variable, you add another number in brackets. For instance, if we added the age variable to the first line of code, age would be added after a comma in the variable list and the string would contain a {1} to indicate that the second variable should be used. Remember that any computer value starts with 0, so the replacement characters also start with 0.
After you complete the program, you can compile and run it from the Visual Studio IDE. In the top menu of the IDE, you see a green arrow labeled "Start." Click it, and your program runs in the console. When you use this button, you automatically run the program in the debugger, which is the testing environment in Visual Studio. Enter input when prompted and test your program. You can even throw incorrect data to see the program crash. Proper testing should find bugs including logic and input validation errors.
This simple program gives you practice with user input. Remember that we skipped validation and error checking. You'll need to add coded logic that identifies if any incorrect data is entered that could crash the program. With some practice, you'll be able to work with user input and store it in a database or use it to create calculations and return a response back to the user without any errors.