๐ŸŽ“ A1Learner
๐Ÿ”

C# User Input

User input is text a person types while the program runs. Console.ReadLine reads one line of that typed text.

Reading a name

The program prints a prompt and then reads one line. The typed name Hana comes back as a string.

using System;

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

Reading text and a number

The age arrives as text, so Convert.ToInt32 turns it into an int. The program can then add 1 to it.

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter your name:");
        string name = Console.ReadLine();
        Console.WriteLine("Enter your age:");
        int age = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine(name + " is " + age);
        Console.WriteLine("Next year: " + (age + 1));
    }
}

Adding two typed numbers

Each ReadLine call reads one typed number. Convert turns both into ints before the addition.

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter the first number:");
        int first = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter the second number:");
        int second = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Sum: " + (first + second));
    }
}

Example

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter the item:");
        string item = Console.ReadLine();
        Console.WriteLine("Enter the price:");
        double price = Convert.ToDouble(Console.ReadLine());
        Console.WriteLine("Enter the quantity:");
        int quantity = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Total: " + (price * quantity));
    }
}

Key points

  • Console.ReadLine reads one line of typed text.
  • ReadLine always gives the program a string.
  • Convert.ToInt32 turns typed text into an int.
  • Convert.ToDouble turns typed text into a double.
  • A prompt line tells the person what to type.

In this example, the program reads the item Notebook as a string. Convert.ToDouble turns the typed price into 12.5, and Convert.ToInt32 turns the quantity into 3. The last line multiplies price by quantity and prints Total: 37.5.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C# Compiler

Exercise

What type does Console.ReadLine always return?