1

I'm trying to understand what is happening with Console.ReadKey() versus Console.ReadKey(true). I understand that including true will prevent the key from being displayed to the console, but there is some odd behavior produced when also using Console.Clear(); I should say that this C# code is being compiled and run on a Pixel C (android) tablet. I don't know if it behaves the same on Windows.


using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;

namespace CSharp_Shell
{

    public static class Program 
    {
        public static void Main() 
        {
           string[] str = new String[5] {"one","two","three","four","five"};
           foreach(string s in str)
           {
               Console.WriteLine(s);
           }
           Console.ReadKey(true);
           Console.Clear();
           foreach(string s in str)
           {
               Console.WriteLine(s);
           }
        }
    }
}

When executed, this console will display...

one
two
three
four
five

...after which I can press a key, clearing the console, and displaying the text again.

However, if I change Console.ReadKey(true); to Console.ReadKey(); then the execution produces the initial text as expected, and after pressing a key only displays...

one
two

Finally, running the code in the two ways described above but with the additional change of removing the Console.Clear(); line results in all the text being displayed as expected (without the screen clearing), with the difference being that when using Console.ReadKey(); any displayable key pressed is also written to the console (which I would expect).

Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
Bosco312
  • 11
  • 1
  • `Console.Out.Flush();`? – Sani Huttunen Jul 07 '19 at 23:26
  • The compiler doesn't recognize `Console.Out.Flush();` and Microsoft's .NET help pages only list `Console.Out`, nothing about `Flush()`. Can you (or someone) be more verbose in their explanation? Perhaps include an example of how that would fit into my code. – Bosco312 Jul 08 '19 at 00:08
  • It does not behave the same on Windows...it does as expected. – Chris Catignani Jul 08 '19 at 01:32
  • Might be the issue with compiler or .NET Framework version because I've tested your code in all 4 cases and its working completely fine. You can see it here [ https://onlinegdb.com/S1QexuxbH ]. Code is absolutely OK – TalESid Jul 08 '19 at 07:32

0 Answers0