How to pause a Console application in C# or the equivelent to the C++ system("pause") statement?
How to pause a Console application in C# or the equivelent to the C++ system(“pause”) statement?
I actually had to spend way more time to figure this out. I assumed that there was a simple pause function, but there is not. C# has left out that function. So if you are looking for a way to do this with a single statement, you are not going to find it. I searched, and searched, and searched.
I just wanted to pause, something that is common in C++. In C++ people always do the following:
system("pause");
Note: This is not actually an efficient method to do this in C++. It is loading a cmd.exe process and running the pause
command inside it. So should you really be loading a separate external process and all its resources every time you want to pause? Well, it isn’t really that many resources so who really cares, right? You could do the same thing in C# by launching a cmd.exe process but it is probably not what you really want to do.
The best solutions I found are documented, one uses a function, one uses a Pause class.
How to pause a Console application in C#?
Step 1 – Create a function in your Program.cs class called pause as shown here:
public static void Pause() { Console.Write("Press any key to continue . . . "); Console.ReadKey(true); }
Step 2 – Call this function in your code. The following is a complete example
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Pause { class Program { static void Main(string[] args) { Pause(); } public static void Pause() { Console.Write("Press any key to continue . . ."); Console.ReadKey(true); } } }
How to do this as a Pause class?
Step 1 – Create the following class
Pause.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Pause { class Pause { public Pause() { Console.Write("Press any key to continue . . ."); Console.ReadKey(true); } } }
Step 2 – Add this to your project and then call new Pause();
and you did it. As
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Pause { class Program { static void Main(string[] args) { new Pause(); } } }