3

Is there a way to write a message inside of Console.ReadLine()

Like:

Console.ReadLine("What is your name: ");
d51
  • 316
  • 1
  • 6
  • 23
  • 3
    It sounds like you're looking for `Console.WriteLine()` or perhaps `Console.Write()`. – David Apr 30 '20 at 23:12

3 Answers3

6

No, the only way is to write a message before reading a line. Use Console.Write() instead of Console.WriteLine() to prevent outputting a newline.

Console.Write("What is your name: ");
string name = Console.ReadLine();
thesilican
  • 581
  • 5
  • 17
4

ReadLine is not like a Dialog Box, where you can give the user output, about what input you want.

If you want to tell the user what to do, you need a seperate Console.WriteLine() to do so.

Console.WriteLine("What is your name: ");
var input = Console.ReadLine();
Christopher
  • 9,634
  • 2
  • 17
  • 31
4

There is no way to do exactly what you've asked, but you can write a helper method for this.

Here's a simple example of a method that takes in a string that will be displayed to the user, and returns the string that the user enters:

public static string GetStringFromUser(string prompt)
{
    Console.Write(prompt);
    return Console.ReadLine();
}

Now this can be used like:

string userName = GetStringFromUser("Please enter your name: ");
Console.WriteLine($"Hello, {userName}!");

Output

enter image description here

Rufus L
  • 36,127
  • 5
  • 30
  • 43