0
0
CsharpHow-ToBeginner · 3 min read

How to Use Console.ReadLine in C# for User Input

Use Console.ReadLine() in C# to read a line of text input from the user via the console. It returns the input as a string, which you can store in a variable for further use.
📐

Syntax

The basic syntax of Console.ReadLine() is simple. It reads a full line of text entered by the user until they press Enter.

  • Console.ReadLine(): Reads the input line as a string.
  • Returns string: The text entered by the user.
csharp
string input = Console.ReadLine();
💻

Example

This example shows how to ask the user for their name, read it using Console.ReadLine(), and then greet them.

csharp
using System;

class Program
{
    static void Main()
    {
        Console.Write("Enter your name: ");
        string name = Console.ReadLine();
        Console.WriteLine($"Hello, {name}!");
    }
}
Output
Enter your name: Alice Hello, Alice!
⚠️

Common Pitfalls

Some common mistakes when using Console.ReadLine() include:

  • Not storing the returned string, so the input is lost.
  • Assuming the input is not null or empty without checking.
  • Trying to read other data types directly without converting the string.

Always validate or convert the input as needed.

csharp
/* Wrong way: ignoring input */
Console.ReadLine();

/* Right way: store input and check */
string input = Console.ReadLine();
if (!string.IsNullOrEmpty(input))
{
    Console.WriteLine($"You typed: {input}");
}
📊

Quick Reference

FeatureDescription
Console.ReadLine()Reads a line of text input from the console as a string.
Return Typestring
UsageStore the result in a string variable to use the input.
ConversionConvert string to other types if needed (e.g., int.Parse).
Null CheckCheck for null or empty input to avoid errors.

Key Takeaways

Use Console.ReadLine() to read user input as a string from the console.
Always store the returned string to use the input later.
Validate or convert the input string before using it in your program.
Console.ReadLine() waits for the user to press Enter before returning.
Check for null or empty input to avoid runtime errors.