C# User Input

C# User Input

1 - Get User Input

You have already learned that Console.WriteLine() is used to output (print) values. Now we will use Console.ReadLine() to get user input.

In the following example, the user can input his or hers username, which is stored in the variable userName. Then we print the value of userName:

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            // Type your username and press enter
            Console.WriteLine("Enter username:");

            // Create a string variable and get user input 
            // from the keyboard and store it in the variable
            string userName = Console.ReadLine();

            // Print the value of the variable (userName),
            // which will display the input value
            Console.WriteLine("Username is: " + userName);
            Console.ReadLine();
        }
    }
}

Output:

C# Get User Input Example

2 - User Input and Numbers

The Console.ReadLine() method returns a string. Therefore, you cannot get information from another data type, such as int

The following program will cause an error:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

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

The error message will be like this:

Cannot implicitly convert type 'string' to 'int' 

C# User Input and Numbers

Like the error message says, you cannot implicitly convert type 'string' to 'int'.

Luckily, for you, you just learned from the previous chapter (Type Casting), that you can convert any type explicitly, by using one of the Convert.To methods.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

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

Output:

C# Convert Example