C# Beginners – User Input

C# Logo - C# Beginners Input & Selection
C# Logo

Introduction – C# Beginners – User Input

C# Beginners Input & Selection; is a guide to taking input from the user using the Console. Next, it will cover casting between strings and integers, introducing the int try parse function. This post assumes you have chosen an IDE and are comfortable creating variables, the basic data types and running a C# program in your preferred IDE. If one or more of those isn’t true, please see some of the earlier posts in this series here.

Taking User Input

Getting the user to provide input from the Console is a simple, single line of code.

string? userInput = Console.ReadLine();

In the line above, ‘string’ is the data type, ‘userInput’ is the variable name and Console.ReadLine() is the instruction. In a single line, we declare a variable of type string called userInput and then assign the return value from Console.ReadLine().

It is important to note that any input from the Console is always a string. This can provide us with some challenges. For example, if we want a user to provide something numerical, that number must be parsed into a numerical data type. There are several approaches to doing this. The simplest is to use ‘int.parse; or double.parse’.

string? userInput = Console.ReadLine();
int numInt = int.Parse(userInput);
double numDbl = double.Parse(userInput);

Unfortunately, this presents a problem; users are notoriously bad at typing in a way we would like them to. For example, typing the word ‘ten’ instead of ’10’ would cause the program to crash. Similarly, if the user added an extra space before or after, it would also cause a crash. See the sample output below.

User Types Correctly

Please enter a number
10

Process finished with exit code 0.

User Types Incorrectly

Please enter a number
ten
Unhandled exception. System.FormatException: Input string was not in a correct format.
   at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)
   at System.Number.ParseInt32(ReadOnlySpan`1 value, NumberStyles styles, NumberFormatInfo info)
   at System.Int32.Parse(String s)
   at Program.<Main>$(String[] args) in /home/sara/src/RiderDemo/RiderDemo/Program.cs:line 4

Process finished with exit code 134.

Parsing a better way – try parse

A better way is to use the try parse methods.

Console.WriteLine("Please enter a number");
string? userInput = Console.ReadLine();
bool isInteger = int.TryParse(userInput, out int number);

In the code above, we get a boolean result; if the string can be successfully parsed into an integer, it returns true; otherwise, the result is false. If the parsing is successful, we can access the integer value with the variable ‘number’ in the out statement. I will not explain how that works for now, but it will be covered in a later tutorial. Parsing to doubles or other data types is done in an almost identical way. Try the code below using both ‘ten’ and ’10’ as the console input.

Console.WriteLine("Please enter a number");
string? userInput = Console.ReadLine();
bool isInteger = int.TryParse(userInput, out int number);
Please enter a number
10
10 isInteger: True
10 isDouble: True

Process finished with exit code 0.
Please enter a number
ten
ten isInteger: False
ten isDouble: False

Process finished with exit code 0.

Don’t forget if the conversion is successful, we can also access the output. Try the code below and use 10 as the console input.

Console.WriteLine("Please enter a number");
string? userInput = Console.ReadLine();
bool isInteger = int.TryParse(userInput, out int intNumber);
bool isDouble = double.TryParse(userInput, out double dblNumber);
double result = intNumber * dblNumber;
Console.WriteLine(userInput + " isInteger: " + isInteger);
Console.WriteLine(userInput + " isDouble: " + isDouble);
Console.WriteLine("Result: " + result);

Output

Please enter a number
10
10 isInteger: True
10 isDouble: True
Result: 100

Process finished with exit code 0.

This code is much better, but it is still not foolproof. Test it and see what happens if you enter ‘ten’ into the Console again.

Please enter a number
ten
ten isInteger: False
ten isDouble: False
Result: 0

The default value for the output if the parsing fails is 0. It is, however, unlikely that it will be a number you, as the programmer, will want the program to use.

The way to fix this further is by using selection. Selection (if/else if/else) is the following tutorial in this C# for beginners series. I will add an example of this code with the selection below for clarity.

Console.WriteLine("Please enter a number");
string? userInput = Console.ReadLine();
bool isInteger = int.TryParse(userInput, out int intNumber);
bool isDouble = double.TryParse(userInput, out double dblNumber);
double result = intNumber * dblNumber;
if (isInteger)
{
    Console.WriteLine(userInput + " can be parsed to an integer");
}
else
{
    Console.WriteLine(userInput + " can not be parsed to an integer");
}

if (isDouble)
{
    Console.WriteLine(userInput + " can be parsed to a double");
}
else
{
    Console.WriteLine(userInput + " can not be parsed to a double");
}

Output Examples

Please enter a number
10
10 can be parsed to an integer
10 can be parsed to a double

Process finished with exit code 0.
Please enter a number
ten
ten can not be parsed to an integer
ten can not be parsed to a double

Process finished with exit code 0.

Video Version – C# Beginners – User Input

Note For Vs-Code Users

By default, VsC-de doesn’t allow you to take user input from the console. To achieve this, a few steps must be followed.

  • Open the folder you will work in for the C# Solution.
  • Save a VsCode Workspace; this will generate a .vscode colder inside it with several settings.
  • Open the launch.json file inside the .vscode directory.

Change

"console": "internalConsole",
"console": "integratedTerminal",

Save the file and run the program. The effect is it now launches in a terminal that does support console input. This is not only true for C#. It is valid for all languages that use console input.

Related Articles – C# Beginners – User Input

Related Post

9 thoughts on “C# Beginners – User Input

Leave a Reply

Your email address will not be published. Required fields are marked *