Is there a way to write a message inside of Console.ReadLine()
Like:
Console.ReadLine("What is your name: ");
Is there a way to write a message inside of Console.ReadLine()
Like:
Console.ReadLine("What is your name: ");
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();
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();
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