Oellemans
Oellemans

Reputation: 136

Why does my console application disappear immediately

I've made a Console Application is Microsoft Visual Studio 2012. This is what i've added to my code.

    static void Main(string[] args)
    {
        Console.WriteLine("Hello World");
    }

When I'm debugging this program, the program close immediatly! What am I doing wrong?

Upvotes: 4

Views: 1145

Answers (7)

Paul Michaels
Paul Michaels

Reputation: 16705

Al the existing answers are correct, but Ctrl-F5 (instead of just F5 in VS) to run will also have the effect of waiting for a keystroke.

EDIT

The above will not allow you to debug as such, but you don't have a breakpoint in there anyway. Pressing F10 will step through the program line by line.

Upvotes: 2

Adil
Adil

Reputation: 148180

Because the only statement you have just prints a line and the execution of program is finished and program is exited. Use Console.ReadLine Line to stop window to get disappear. Use read line will exit program when Enter key is pressed.

You can use ReadKey if you want to do like "Press any key to continue..." The will cause the program to exit when any key is pressed.

static void Main(string[] args)
{
    Console.WriteLine("Hello World");
    Console.Read();
}

Upvotes: 0

paul cheung
paul cheung

Reputation: 768

all of the above is correct. Typically, Console.ReadKey() is used for control purpose instead logic processing.

static void Main(string[] args)
{
    Console.WriteLine("Hello World");
    string line = Console.ReadKey();
}

you can get more information here

Upvotes: 0

Matt Webber
Matt Webber

Reputation: 71

You could just add

Console.ReadKey();

This will await a keystroke before closing the program.

Upvotes: 0

Chris Shao
Chris Shao

Reputation: 8231

You should add Console.ReadLine(); after WriteLine method, So your application will wait user to input. After user pressed any keys, Your application will disappear.

   static void Main(string[] args)
    {
        Console.WriteLine("Hello World");
        Console.ReadLine();
    }

Upvotes: 0

Jevgeni Geurtsen
Jevgeni Geurtsen

Reputation: 3133

You have to add Console.ReadLine() to the end of the Main method, this will make the console wait until the user sends any input to the console and then it will exit.

Upvotes: 3

Dhaval Patel
Dhaval Patel

Reputation: 7601

you have to write the

Console.WriteLine("Hello World");
Console.ReadLine();

Upvotes: 0

Related Questions