C# User Input - Complete Guide
Introduction to User Input
Getting user input is essential for interactive C# applications. The Console class in the System namespace provides methods for reading input from the user through the command line.
C# offers several approaches to capture user input, from simple text entry to more complex parsing of different data types. Understanding how to properly handle user input is crucial for creating robust applications that can handle various user interactions.
Basic Input Methods
The Console class provides three main methods for reading user input:
Example
using System;
namespace BasicInputExample
{
class Program
{
static void Main(string[] args)
{
// ReadLine() - reads entire line until Enter is pressed
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.Write("Enter your age: ");
string ageInput = Console.ReadLine();
Console.WriteLine($"Hello {name}, you are {ageInput} years old!");
// Read() - reads single character, returns ASCII value
Console.Write("Press any key to continue: ");
int key = Console.Read();
Console.WriteLine($"\nYou pressed: {(char)key} (ASCII: {key})");
// ReadKey() - reads single key press, returns ConsoleKeyInfo
Console.Write("Press any key to exit: ");
ConsoleKeyInfo keyInfo = Console.ReadKey();
Console.WriteLine($"\nYou pressed: {keyInfo.Key} (Char: {keyInfo.KeyChar})");
// Clearing the input buffer (important after using Read())
while (Console.In.Peek() != -1)
{
Console.In.Read();
}
}
}
}
Output
Enter your name: John Enter your age: 25 Hello John, you are 25 years old! Press any key to continue: a You pressed: a (ASCII: 97) Press any key to exit: x You pressed: X (Char: x)
Parsing and Validating Input
User input often needs to be parsed and validated to ensure it's in the correct format:
Example
using System;
namespace InputValidationExample
{
class Program
{
static void Main(string[] args)
{
// Integer input with validation
int age;
bool validAge = false;
while (!validAge)
{
Console.Write("Enter your age: ");
string input = Console.ReadLine();
if (int.TryParse(input, out age) && age > 0 && age < 120)
{
Console.WriteLine($"Valid age: {age}");
validAge = true;
}
else
{
Console.WriteLine("Invalid age. Please enter a number between 1 and 119.");
}
}
// Double input with validation
double price;
bool validPrice = false;
while (!validPrice)
{
Console.Write("Enter product price: ");
string input = Console.ReadLine();
if (double.TryParse(input, out price) && price > 0)
{
Console.WriteLine($"Valid price: {price:C}");
validPrice = true;
}
else
{
Console.WriteLine("Invalid price. Please enter a positive number.");
}
}
// DateTime input with validation
DateTime birthDate;
bool validDate = false;
while (!validDate)
{
Console.Write("Enter your birth date (yyyy-mm-dd): ");
string input = Console.ReadLine();
if (DateTime.TryParse(input, out birthDate) && birthDate < DateTime.Now)
{
Console.WriteLine($"Valid date: {birthDate:yyyy-MM-dd}");
validDate = true;
}
else
{
Console.WriteLine("Invalid date. Please enter a valid date in the past.");
}
}
// Boolean input with validation
bool isStudent;
bool validBool = false;
while (!validBool)
{
Console.Write("Are you a student? (yes/no): ");
string input = Console.ReadLine()?.ToLower();
if (input == "yes" || input == "y")
{
isStudent = true;
validBool = true;
}
else if (input == "no" || input == "n")
{
isStudent = false;
validBool = true;
}
else
{
Console.WriteLine("Please answer 'yes' or 'no'.");
}
}
Console.WriteLine($"Student status: {isStudent}");
}
}
}
Output
Enter your age: 25 Valid age: 25 Enter product price: 19.99 Valid price: $19.99 Enter your birth date (yyyy-mm-dd): 1998-05-15 Valid date: 1998-05-15 Are you a student? (yes/no): yes Student status: True
Advanced Input Techniques
For more complex applications, you might need advanced input handling techniques:
Example
using System;
using System.Collections.Generic;
namespace AdvancedInputExample
{
class Program
{
static void Main(string[] args)
{
// Menu system with input
bool running = true;
while (running)
{
Console.WriteLine("\n=== MENU ===");
Console.WriteLine("1. Add item");
Console.WriteLine("2. View items");
Console.WriteLine("3. Exit");
Console.Write("Select an option: ");
string input = Console.ReadLine();
switch (input)
{
case "1":
Console.Write("Enter item name: ");
string itemName = Console.ReadLine();
Console.WriteLine($"Added: {itemName}");
break;
case "2":
Console.WriteLine("Viewing items...");
// Simulated items
Console.WriteLine("- Item 1");
Console.WriteLine("- Item 2");
break;
case "3":
Console.WriteLine("Goodbye!");
running = false;
break;
default:
Console.WriteLine("Invalid option. Please try again.");
break;
}
}
// Password input (hiding characters)
Console.Write("Enter password: ");
string password = "";
ConsoleKeyInfo keyInfo;
do
{
keyInfo = Console.ReadKey(true);
// Skip if Backspace or Enter
if (keyInfo.Key != ConsoleKey.Backspace && keyInfo.Key != ConsoleKey.Enter)
{
password += keyInfo.KeyChar;
Console.Write("*");
}
else if (keyInfo.Key == ConsoleKey.Backspace && password.Length > 0)
{
password = password.Substring(0, password.Length - 1);
Console.Write("\b \b"); // Erase the last asterisk
}
} while (keyInfo.Key != ConsoleKey.Enter);
Console.WriteLine($"\nYour password is: {password}");
// Multiple inputs in one line
Console.Write("Enter name, age, and city (comma-separated): ");
string multiInput = Console.ReadLine();
string[] inputs = multiInput.Split(',');
if (inputs.Length >= 3)
{
string userName = inputs[0].Trim();
string userAge = inputs[1].Trim();
string userCity = inputs[2].Trim();
Console.WriteLine($"Name: {userName}, Age: {userAge}, City: {userCity}");
}
else
{
Console.WriteLine("Invalid input format.");
}
}
}
}
Output
=== MENU === 1. Add item 2. View items 3. Exit Select an option: 1 Enter item name: Book Added: Book === MENU === 1. Add item 2. View items 3. Exit Select an option: 3 Goodbye! Enter password: ******** Your password is: secret123 Enter name, age, and city (comma-separated): John, 25, New York Name: John, Age: 25, City: New York