C# User Input
Getting user input.
C# User Input
You have already learned that Console.WriteLine() is used to output (print) values. Now we will use Console.ReadLine() to get user input.
In the following example, the user can input his or hers username, which is stored in the variable userName. Then we print the value of userName:
User Input and Numbers
The Console.ReadLine() method returns a string. Therefore, you cannot get information from another data type, such as int.
If you want to read a number, you must explicitly convert the user input to the correct type (like int), using one of the Convert.To methods.
Examples
Get User String
Reading a string from the user.
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter username:");
string userName = Console.ReadLine();
Console.WriteLine("Username is: " + userName);
}
}Get User Number
Reading a number requires conversion.
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter your age:");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your age is: " + age);
}
}Simple Calculator
Adding two numbers from user input.
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number:");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter another number:");
int y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Sum is: " + (x + y));
}
}