C# User Input
C# provides various ways to read user input, primarily using the Console
class. You can read input as strings, characters, or key presses, making applications interactive.
Key Topics
- Reading Input as a String
- Reading Input as an Integer
- Reading a Single Character
- Reading Key Presses
1. Reading Input as a String
Console.ReadLine()
is the most common way to read user input as a string. It reads the entire input until the user presses Enter.
Example
// Reading user input as a string
Console.WriteLine("Enter your name:");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name + "!");
Output:
Explanation: The input is stored in the string variable name
and printed with a greeting. The input is captured until the Enter key is pressed.
2. Reading Input as an Integer
Console.ReadLine()
reads input as a string, but you can convert it to an integer using Convert.ToInt32()
or int.Parse()
.
Example
// Reading input as an integer
Console.WriteLine("Enter your age:");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("You are " + age + " years old.");
Output:
Explanation: The string input is converted into an integer using Convert.ToInt32()
and printed as an integer value.
3. Reading a Single Character
Console.Read()
reads a single character and returns its ASCII value. This is useful when you want to capture one key press without needing to press Enter.
Example
// Reading a single character
Console.WriteLine("Press any key to continue...");
int asciiValue = Console.Read();
char key = (char)asciiValue;
Console.WriteLine("You pressed: " + key);
Console.WriteLine("ASCII value: " + asciiValue);
Output:
Explanation: Console.Read()
returns the ASCII code of the pressed key, which is then converted to a character and displayed.
4. Reading Key Presses with Console.ReadKey()
Console.ReadKey()
reads a single key press and provides more information about the key, such as whether modifier keys (like Shift) were pressed.
Example
// Reading key presses with detailed information
Console.WriteLine("Press a key:");
ConsoleKeyInfo keyInfo = Console.ReadKey();
Console.WriteLine();
Console.WriteLine("You pressed: " + keyInfo.Key);
Console.WriteLine("Key code: " + keyInfo.KeyChar);
Console.WriteLine("Modifiers: " + keyInfo.Modifiers);
Output:
Explanation: The ConsoleKeyInfo
object captures detailed information about the key press, including the key itself, the key character, and any modifier keys (such as Shift or Ctrl).