Data Input and Data Conversion
So far all of our examples use literal data values. It is more common in programming for data to come from numerous sources, such as user input, databases, files, or over the network. Here we look briefly at capturing data from user inputs.
The simplest and most common way to capture user input is to use Console.ReadLine()
Notice the datatype for userInput
is a string
. Console.ReadLine() always returns a String. So if you want to handle other types you will have to use a conversion method to convert from a String to the required type.
All the primitive types and complex datatypes have conversion methods. For example
If the user input value is not compatible with the type you are trying to convert it to, an exception will be thrown
Consider using int.TryParse(userInput);
when you think there might an issue where the user might type in a value that does not match the desired type.