0

I am just getting started with visual studio and c#. When i run the code the console exits right away.

Lets say I have the following code :

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello world");

    }
}

I wont have the time to see the results, because the console closes so quickly after running. In a tutorial I am watching (which is an older version of visual studio) The guy is able to see his results. In his screen it shows : Press any key to continue and THEN it closes. Not right away. How can I configure my visual studio to do this?

I can solve this by using Console.Readline(); is there any other way?

Kevin.a
  • 4,094
  • 8
  • 46
  • 82
  • Program terminates when there's nothing left to do. VS 2019 actually pauses after the console app terminates to let you examine the console output, but it's VS doing that, not the program. – 500 - Internal Server Error May 05 '20 at 17:38
  • Is there a way to make it pause after the code executed. I am using the latest community edition. @500-InternalServerError – Kevin.a May 05 '20 at 17:45
  • Are you running in a debugger (Ctrl+F5)? – Joe Sewell May 05 '20 at 17:45
  • @JoeSewell I just did f5 before, now i tried ctrl + f5 and that did the trick. Thank you – Kevin.a May 05 '20 at 17:46
  • Does this answer your question? [Why is the console window closing immediately once displayed my output?](https://stackoverflow.com/questions/8868338/why-is-the-console-window-closing-immediately-once-displayed-my-output) – Lance U. Matthews May 05 '20 at 18:26

2 Answers2

0

In console mode, the program will be closed after the execution. To prevent that, you have 3 options.

  1. Exports logs in a file so you can read it after execution
  2. Put a console.readline() at the end of your code to prevent closing
  3. put a sleep time to let you the time to read (totally not my favorite one)
Blazkowicz
  • 180
  • 9
0

If you want for the program to pause at the end also when you are not running it with Ctrl + F5, you can use:

Console.Readline();

as @Blazkowicz wrote, but note that the console will then be waiting specifically for the Enter key to shut down. It will also continue printing input from the user to the console. If you want to avoid this, you can use:

Console.ReadKey(true);

ReadKey() can take the intercept bool which, if true, will stop user input from being printed.

rzeczuchy
  • 13
  • 4