Reputation: 333
I have a question about this code, which is simply supposed to write what I'm typing.
ConsoleKeyInfo a = Console.ReadKey();
if (a.Key == ConsoleKey.Spacebar)
{
Console.Write(" ");
}
else if (a.Key == ConsoleKey.Enter)
{
Console.WriteLine("");
}
else
{
string b = a.Key.ToString();
Console.Write(b);
}
If I'm clicking on d for example it prints:
dD
but if I check b.Length
it equals 1. and if I try to print b[0]
it is still printing dD
. How is that possible? And how can I fix it?
Upvotes: 0
Views: 155
Reputation: 3388
It's not printing dD
, it is printing D
which is the value of a.Key.ToString()
. It is putting it immediately after d
so in the console it looks like dD
.
Upvotes: 0
Reputation: 754725
The ReadKey
method both reads a key and displays it to the user. Hence when you hit "d" it displays "d", returns a ConsoleKeyInfo
value and then your code displays "D". This results in the "dD" display.
To stop this pass true
to ReadKey
to prevent the display
ConsoleInfo a = Console.ReadKey(true);
Upvotes: 3