Console.Read and Console.ReadLine functions

We used Console.Write and Console.WriteLine methods in the previous tutorial to print the output on the screen. Console.Read and Console.ReadLine methods are used when you want to take some keyboard input from the user.

Important thing to know about keyboard inputs

The first and the most important thing you should understand when reading some keyboard input from the user is that all the inputs are considered as string. No matter if the user is typing “Hello” or “h” or “1” or “123” or “$” each of them will be treated as a string by the C# program. It is the responsibility of the programmer to convert these inputs into proper types before using them in the program.

Difference between Console.Read and Console.ReadLine methods

The Console.Read method reads one character at a time from the keyboard and it returns the ASCII value of the character which you press. If you wish to read some string input from the keyboard using the Console.Read method then you will have to use a loop to capture all the keys pressed by the user from the keyboard. In this program see how we read the input value from the user and print it on the console

static void Main(string[] args)  {          Console.Write("Press a key : ");            // User input is stored in an integer variable          int X = Console.Read();            Console.Write("The ASCII value of the key pressed is : " +X);  }

Output

Console.Read() in C#
 
The Console.ReadLine method on the other hand is used to read string inputs from the keyboard. For example if you want the user to enter his name from the keyboard then you will be using the Console.ReadLine method. This method always returns a string and you will have to convert the input into appropriate type.

static void Main(string[] args)  {          Console.Write("Enter your name : ");            // We are taking a string variable to store the          // input we will get from Console.ReadLine() methods          string userInput = Console.ReadLine();            Console.Write("Hello : " + userInput);  }

Output

Console.ReadLine() output in C#
 

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp