C# – Read From Console

In C#, you can read input from user through console using Console.ReadLine() function. Console.ReadLine() reads the input entered by user until enter is pressed, and the value is returned.

We can store the returned value in a variable and access it.

In the following sections, we will learn how to read a string and a number from console with the help of examples.

C# – How to Read String From Console

By default Console.ReadLine() reads string, from the console, entered by user. We are storing the value into a string and printing it in the next statement.

Program.cs

using System;

namespace CSharpExamples {

    class Program {
        static void Main(string[] args) {
            Console.Write("Enter string: ");
            String str = Console.ReadLine();
            Console.WriteLine("You entered \""+str+"\" in the console.");
        }
    }
}

Output

PS D:\workspace\csharp\HelloWorld> dotnet run
Enter string: TutorialKart
You entered "TutorialKart" in the console.

C# – How to Read a Number From Console

We can read a number from the console using Console.ReadLine(). The trick here is, read the input from user as a string and convert it to integer.

Program.cs

using System;

namespace CSharpExamples {

    class Program {
        static void Main(string[] args) {
            Console.Write("Enter number: ");
            int n = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("You entered the number, "+n+" in console.");
        }
    }
}

Output

PS D:\workspace\csharp\HelloWorld> dotnet run
Enter number: 65
You entered the number, 65 in console.

Conclusion

In this C# Tutorial, we read input entered by the user in console using Console.ReadLine() function.