C# User Input

Getting input from users in your programs

⌨️ What is User Input?

User input allows your program to receive data from users through the keyboard. This makes programs interactive, enabling users to provide information, make choices, and control program behavior dynamically.


// Getting user input
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name + "!");

// Example output if user types "Alice":
// Hello, Alice!
                                    

Output:

Enter your name: Alice

Hello, Alice!

Input Methods

📝

ReadLine()

Read a line of text from user

string input = Console.ReadLine();
🔤

Read()

Read a single character

int charCode = Console.Read();
🔑

ReadKey()

Read a key press

ConsoleKeyInfo key = Console.ReadKey();
💬

Write()

Display prompt for input

Console.Write("Enter: ");

🔹 Reading String Input

The Console.ReadLine() method is the primary way to capture textual user input in a console application. It reads the entire line of input as a string until the user presses the Enter key. This string can then be stored in a variable, manipulated, or validated. For example, you can prompt for a user's name and city to create a personalized greeting. It's important to remember that ReadLine() always returns a string, so any subsequent numeric operations require conversion using int.Parse, Convert, or TryParse methods.

// Reading string input
Console.Write("Enter your name: ");
string name = Console.ReadLine();

Console.Write("Enter your city: ");
string city = Console.ReadLine();

Console.WriteLine("Hello " + name + " from " + city + "!");

// Example interaction:
// Enter your name: John
// Enter your city: New York
// Hello John from New York!

Output:

Enter your name: John

Enter your city: New York

Hello John from New York!

🔹 Reading Numeric Input

Reading numeric input requires converting the string from Console.ReadLine() into a numeric type like int or double. This is a two-step process: first capture the input as a string, then convert it using a method like int.Parse(userInput) or the safer int.TryParse(userInput, out int age). Once converted, the value can be used in calculations, comparisons, and other logic. Proper handling includes implementing validation to manage non-numeric inputs gracefully, which is crucial for creating user-friendly and crash-resistant console applications.

// Reading integer input
Console.Write("Enter your age: ");
string ageInput = Console.ReadLine();
int age = int.Parse(ageInput);

Console.WriteLine("You are " + age + " years old.");
Console.WriteLine("Next year you will be " + (age + 1));

// Shorter version
Console.Write("Enter a number: ");
int number = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your number is: " + number);

// Example:
// Enter your age: 25
// You are 25 years old.
// Next year you will be 26

Output:

Enter your age: 25

You are 25 years old.

Next year you will be 26

🔹 Reading Decimal Input

For precise financial or scientific calculations, reading decimal input requires conversion to decimal or double types. After obtaining a string via Console.ReadLine(), use decimal.Parse() or double.Parse()—preferably their TryParse variants—to handle values with fractional parts. The decimal type is ideal for monetary calculations due to its higher precision and avoidance of rounding errors common in floating-point types. This process is essential for applications dealing with prices, measurements, interest rates, or any domain where accuracy beyond whole numbers is critical.

// Reading decimal input
Console.Write("Enter the price: ");
double price = Convert.ToDouble(Console.ReadLine());

Console.Write("Enter the quantity: ");
int quantity = int.Parse(Console.ReadLine());

double total = price * quantity;
Console.WriteLine("Total cost: $" + total);

// Example:
// Enter the price: 19.99
// Enter the quantity: 3
// Total cost: $59.97

Output:

Enter the price: 19.99

Enter the quantity: 3

Total cost: $59.97

🔹 Multiple Inputs

Design a user-friendly registration interface by prompting for individual details like first name, last name, age, and email. Each input is captured and stored separately, enabling structured data handling. After collection, you can display a formatted summary, enhancing user experience and ensuring data integrity in applications like account creation or profile management systems.

// Collecting multiple inputs
Console.WriteLine("=== User Registration ===");

Console.Write("First Name: ");
string firstName = Console.ReadLine();

Console.Write("Last Name: ");
string lastName = Console.ReadLine();

Console.Write("Age: ");
int age = int.Parse(Console.ReadLine());

Console.Write("Email: ");
string email = Console.ReadLine();

// Display collected information
Console.WriteLine("\n=== Your Information ===");
Console.WriteLine("Name: " + firstName + " " + lastName);
Console.WriteLine("Age: " + age);
Console.WriteLine("Email: " + email);

Output:

=== User Registration ===

First Name: John

Last Name: Doe

Age: 30

Email: [email protected]

=== Your Information ===

Name: John Doe

Age: 30

Email: [email protected]

🔹 Simple Calculator Example

Create an interactive calculator by combining user inputs with arithmetic operators in C#. Prompt users to enter two numbers, then perform and display results for addition, subtraction, multiplication, and division. This practical example illustrates how to transform raw input into functional outputs, making your programs dynamic, educational, and useful for real-world problem-solving.

// Simple calculator
Console.WriteLine("=== Simple Calculator ===");

Console.Write("Enter first number: ");
double num1 = Convert.ToDouble(Console.ReadLine());

Console.Write("Enter second number: ");
double num2 = Convert.ToDouble(Console.ReadLine());

// Perform calculations
double sum = num1 + num2;
double difference = num1 - num2;
double product = num1 * num2;
double quotient = num1 / num2;

// Display results
Console.WriteLine("\nResults:");
Console.WriteLine(num1 + " + " + num2 + " = " + sum);
Console.WriteLine(num1 + " - " + num2 + " = " + difference);
Console.WriteLine(num1 + " * " + num2 + " = " + product);
Console.WriteLine(num1 + " / " + num2 + " = " + quotient);

Output:

=== Simple Calculator ===

Enter first number: 10

Enter second number: 5

Results:

10 + 5 = 15

10 - 5 = 5

10 * 5 = 50

10 / 5 = 2

🔹 Safe Input with TryParse

Ensure robust and error-resistant programs by using TryParse for input validation in C#. This method attempts to convert user input safely, returning a boolean to indicate success or failure. By gracefully handling invalid entries—like non-numeric age input—you prevent crashes, improve user experience, and maintain application stability in professional environments.

// Safe input handling
Console.Write("Enter your age: ");
string input = Console.ReadLine();

int age;
bool isValid = int.TryParse(input, out age);

if (isValid)
{
    Console.WriteLine("Your age is: " + age);
    Console.WriteLine("Valid input!");
}
else
{
    Console.WriteLine("Invalid input! Please enter a number.");
}

// Example with valid input:
// Enter your age: 25
// Your age is: 25
// Valid input!

// Example with invalid input:
// Enter your age: abc
// Invalid input! Please enter a number.

Output (valid input):

Enter your age: 25

Your age is: 25

Valid input!

🧠 Test Your Knowledge

Which method is used to read a line of text from the user?