This Angular tutorial helps you get started with Angular quickly and effectively through many practical examples.

C# - User Input


In C#, you can create a console application that allows users to interact with your program via the command line. You have already learned that Console.WriteLine() is used to output (print) values on console. Now we will use Console.ReadLine() to get user input. In the following example, the user can input his or hers name, which is stored in the variable name. Then we print the value of name using Console.WriteLine().

Example

using System;

namespace FirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter Name:");       
            string name = Console.ReadLine();           
            Console.WriteLine("My name is: " + name);
        }
    }
}

Output

Now run the application.

C# User Input

Now enter the name- Rohatash

C# User Input

The Console.ReadLine() method returns a string. you cannot get information from another data type without convert such as int. The following program will cause an error like that.

using System;

namespace FirstProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter Age:");       
            int age = Console.ReadLine();           
            Console.WriteLine("Age is: " + age);
        }
    }
}

The following error will show.

C# User Input
Prev Next

Top Articles

  1. Why use C#
  2. How to use comment in C#
  3. How to use variables in C#
  4. How to use keywords in C#