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.
Examples
In the following sections, we will learn how to read a string and a number from console with the help of examples.
1. How to read a 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.
C# Program
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.
2. 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.
C# Program
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.