C# ReadLine() Method

The Console.WriteLine() is a method used in C# to print the entire statement of a single line and transfer control to the next line of the console. Similar to the Console.WriteLine(), the ReadLine() method is used to read the entire line of string or statement value from the user until the Enter key is pressed to transfer control to the next line. In this section, we will understand the ReadLine(), Read() and Readkey() method in details.

C# ReadLine() Method

Console.ReadLine() Method

In C#, the ReadLine() method is a commonly used method or function to take an input from the user until the enter key is pressed. In other words, it is a method that reads each line of string or values from a standard input stream.

It is a predefined method of the Console class (System Namespace). The Console.ReadLine() method reads and only returns the string from the stream output device (console) until a newline character is found. If we want to read a character or numeric value from the user, we need to convert the string to the appropriate data sets.

Syntax

The method throws the following exceptions:

  1. IOException: It occurs if an I/O error arises.
  2. OutOfMemoryException: It occurs if there is insufficient memory to allocate a buffer to return a string.
  3. ArgumentOutOfRangeException: It occurs if the number of characters in the next line that is greater than MaxValue.

Example 1: Let's write a program that takes an input from the user using the ReadLine() method.

Program.cs

Output

C# ReadLine() Method

Example 2: Write a program to print the user's first and last name using the ReadLine() function in C#.

Program2.cs

Output

C# ReadLine() Method

Read() Method

The Read() method in C# is used to read a single character from the user. It is different from the ReadLine() method because the readLine() method receives each line input from the user until the line is finished and control transfer to the next statement to read strings.

Let's write a program to understand the use of the Read() method in C# to print a character.

Program4.cs

Output

C# ReadLine() Method

ReadKey()

The ReadKey() method is used to get the next character, or the user presses any key to exit the program. It holds the screen until the user presses any key from the keyboard. The pressed key will be displayed on the console.

Program5.cs

Output

C# ReadLine() Method




Latest Courses