-7

On Visual Studio, the C# Console application keeps on terminating when I try to run a program. I tested this by just writing Hello World, shown here: (screenshot of what I wrote) When I run it, the command prompt window appears for a second, then immediately closes. Is there a way to fix this?

Wilbur Omae
  • 184
  • 2
  • 11
user7658600
  • 9
  • 1
  • 1
  • 4
    Are you sure it is crashing and not just terminating normally? Try Ctrl+F5, is it kept open then? – Lasse V. Karlsen Mar 11 '17 at 21:03
  • Probably it does not crash, but the window gets closed because the execution of the program completes. Try adding Console.Read(); right before the closing parenthesis of Main method. – burkay Mar 11 '17 at 21:03
  • Please include the code as text, not a screen shot. In general, the easier you make it for others to test your code, the greater your chances of getting a quick answer. Whenever possible, include a [runnable example](http://stackoverflow.com/help/mcve) within the question – Leigh Mar 11 '17 at 23:00

4 Answers4

1

When a console application runs it executes the code and exits, console applications do not have a message loop to keep them alive, it is the same as creating a batch file and double clicking it, the command window will open and then close when execution finishes. If you want then console window to hang around afterwards then you need to use Console.ReadLine(); which will wait for user input before closing (i.e. pressing Enter).

You code (which should be in your question) simply outputs some text to the console and then exits.

Suggested reading Creating a Console Application

Neil Stevens
  • 3,534
  • 6
  • 42
  • 71
1
class Program
{
   static void Main (string[] args)
   {
         Console.WriteLine("Hello World");
         Console.ReadLine();
   }
}

The application is not crashing, it runs and then exits. If you want read the output after it's done you can use Console.ReadLine();

LittleBird
  • 65
  • 9
0

The issue is not crashing really but that all the instructions are executed then the program exits. If you desire to pause, you could insert the statement:

Console.ReadKey();

which will wait for you to type a key to exit.

Wilbur Omae
  • 184
  • 2
  • 11
0
using System;

namespace Hello_World
{
  class Program
  {
       static void Main (string[] args)
       {
             Console.WriteLine("Hello World");
             Console.ReadKey();
       }
   }
 }
Joshua Santiago
  • 127
  • 3
  • 12