C# ยท Chapter 10 of 46

C# User Input

The Console.ReadLine() method reads a line of text typed by the user from the console. It always returns a string, even if the user types a number.

To use the input as a number, you must convert it using Convert.ToInt32(), int.Parse(), or similar methods, since C# is strongly typed.

Syntax
string input = Console.ReadLine();
int number = Convert.ToInt32(input);

Reading text input

Console.ReadLine() pauses the program and waits for the user to type something and press Enter. The typed text is returned as a string.

Reading numeric input

Since ReadLine() returns a string, you need to convert it to a number type before doing math, using Convert.ToInt32() or int.Parse().

Example 1 (csharp)
using System;

class Program {
  static void Main() {
    Console.WriteLine("Enter your name:");
    string name = Console.ReadLine();
    Console.WriteLine("Hello, " + name);
  }
}
Output
Enter your name:
Hello, Amy

The user types 'Amy', and it is printed back in a greeting.

Example 2 (csharp)
using System;

class Program {
  static void Main() {
    Console.WriteLine("Enter a number:");
    int num = Convert.ToInt32(Console.ReadLine());
    Console.WriteLine("You entered: " + num);
  }
}
Output
Enter a number:
You entered: 7

The string input is converted to an int using Convert.ToInt32() before being used.

Key points

  • Console.ReadLine() reads a line of input as a string.
  • Numeric input must be converted before doing math.
  • Convert.ToInt32() and int.Parse() convert strings to integers.
  • The program pauses at ReadLine() until the user presses Enter.
๐Ÿ’ก Note: If the user types invalid text when you expect a number, Convert.ToInt32() or int.Parse() will throw an exception.

๐Ÿ“ Quick Quiz

1. What type does Console.ReadLine() always return?

2. Why must you convert user input before doing math with it?

3. Which method converts a string to an integer?