c-sharp
  1. c-sharp-c-readline-method

C# ReadLine() Method

C# ReadLine() is a method in the Console class that allows a user to input a string from the console and store it in a variable. In this tutorial, we'll discuss the syntax, use, and examples of the ReadLine() method in C#.

Syntax

The syntax for using the ReadLine() method in C# is as follows:

string inputString = Console.ReadLine();

Example

Let's say we want to write a program to ask a user for their name and then greet them. Here's how we can implement it:

using System;

class GreetingProgram
{
    static void Main()
    {
        Console.Write("Please enter your name: ");
        string name = Console.ReadLine();
        Console.WriteLine("Hello, " + name + "!");
    }
}

Output

When we run the example code above, the output will be:

Please enter your name: John
Hello, John!

This is because the program prompts the user to enter their name, reads the input string using the ReadLine() method, and then greets the user using their input name.

Explanation

In the example above, we used the ReadLine() method to read a string input from the console. We prompted the user to enter their name by writing a message to the console using Console.Write(). Then, we called the ReadLine() method to read the user's input and store it in a string variable called "name". Finally, we printed a greeting message to the console using the user's input name.

Use

The ReadLine() method in C# is useful when you want to prompt the user for input and store the result in a variable to be used later in your program. You can use it to create interactive console applications and to get user input for program logic.

Important Points

  • Console.ReadLine() method always returns a string, so you may need to parse the input into a number or other data type if necessary.
  • If there is no more data available in the input stream, ReadLine() will block and wait for input.
  • The input string returned by ReadLine() includes any leading or trailing white space.

Summary

In this tutorial, we discussed how to use the ReadLine() method in C# to read a string input from the console. We covered the syntax, examples, explanation, use, and important points of the ReadLine() method in C#. With this knowledge, you can now use the ReadLine() method in your C# code to prompt users for input and store their input for program logic.

Published on: