Open In App

Console.ReadLine() Method in C#

This method is used to read the next line of characters from the standard input stream. It comes under the Console class(System Namespace). If the standard input device is the keyboard, the ReadLine method blocks until the user presses the Enter key. And if standard input is redirected to a file, then this method reads a line of text from a file. 
 

Syntax: public static string ReadLine ();
Return Value: It returns the next line of characters of string type from the input stream, or null if no more lines are available. 
 


Exceptions: 


Below program illustrate the use of the above-discussed method:
Example 1: Here, take input from the user. Since age is an integer, we typecasted it using Convert.ToInt32() Method. It reads the next line from the input stream. It blocks until Enter key is pressed. Hence it is commonly used to pause the console so that the user can check the output.

// C# program to illustrate
// the use of Console.ReadLine()
using System;
using System.IO;

class GFG {
    
    // Main Method
    public static void Main()
    {
        int age;
        string name;

        Console.WriteLine("Enter your name: ");
        
        // using the method
        // typecasting not needed 
        // as ReadLine returns string
        name = Console.ReadLine();
        
        Console.WriteLine("Enter your age: ");
        
        // Converted string to int
        age = Convert.ToInt32(Console.ReadLine());
        
        if (age >= 18) 
        {
            Console.WriteLine("Hello " + name + "!"
                        + " You can vote");
        }
        else {
            Console.WriteLine("Hello " + name + "!"
                + " Sorry you can't vote");
        }
    } 
}

Output: 

readline-1


Example 2: To pause the console

// C# program to illustrate
// the use of Console.ReadLine()
// to pause the console
using System;
using System.IO;

class Geeks {
    
    // Main Method
    public static void Main()
    {
        string name;
        int n;

        Console.WriteLine("Enter your name: ");
        
        // typecasting not needed as 
        // ReadLine returns string
        name = Console.ReadLine();
        
        Console.WriteLine("Hello " + name + 
             " Welcome to GeeksforGeeks!");
        
        // Pauses the console until 
        // the user presses enter key
        Console.ReadLine(); 
    } 
}

Output: 
 

readline-2


Explanation: In the above output you can see that the console is paused. The cursor will blink continuously until you press Enter key.
Reference: 

Article Tags :
C#