Radu Harabagiu Radu Harabagiu - 2 months ago 7
C# Question

How to write a string using readkey inside a loop?

I am making a program in which I need the user input to be invisible, and I read that

var key = System.Console.ReadKey(true);
does just that.
To do what I need, however I need a string with multiple characters, so what I've done is

string Choice1=null;
User1Input:
while (true)
{
var key = System.Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
{
break;
}
Choice1 += key;
}


What is happening is that
key
simply doesn't read anything, because even if I press enter, the loop does not close.

Answer

So your sole intention is to hide the character while user types input in console. In that case you are in right track and your posted code looks good except the last line which says Choice1 += key;. It should be

Choice1 += key.KeyChar;

Your posted code with bit modification

string choice1=null; //casing of variable names
while (true)
{
    var key = System.Console.ReadKey(true);
    if (key.Key == ConsoleKey.Enter)
        break;

    choice1 += key.KeyChar;
 } 
Comments