Coder Perfect

In C#, what command do you use to terminate a console application?


In C#, what command do you use to terminate a console application?

Asked by Sababoni

Solution #1

You can use Environment.Exit(0); and Application.Exit

Environment.Exit(0) is cleaner.

Answered by Nikhil Agrawal

Solution #2

Several options, by order of most appropriate way:

9/2013 rewrite to increase readability

Returning a specified exit code: As Servy points out in the comments, you may specify Main as an int return type and use that to return an error code. As a result, there is no need to use Environment. Unless you need to end with an exit code and can’t do so in the Main method, exit. You may most likely avoid this by throwing an exception in Main and returning an error code if an unhandled exception propagates there. If your application is multi-threaded, you’ll probably need even more boilerplate to properly terminate with an exit code, so you might as well just call Environment. Exit.

Reusability is another argument against using Evironment.Exit, especially when creating multi-threaded apps. The code will not be portable if you want to reuse it in an environment that ignores Environment.Exit (for example, a library that could be used in a web server). In my opinion, the ideal option is to always utilize exceptions and/or return values that indicate that the method has reached an error/finish state. As a result, the same code may be used in any.NET environment and in any sort of application. You can encapsulate the thread at the highest level if you’re developing a specific program that has to return an exit code or terminate in a similar way to what Environment.Exit does.

Answered by sinelaw

Solution #3

When the primary function has completed, console programs will terminate. This will be accomplished through a “return.”

    static void Main(string[] args)
        while (true)
            Console.WriteLine("I'm running!");
            return; //This will exit the console application's running thread

If you want to return an error code, use this method, which is accessible from functions outside of the main thread:


Answered by Developer

Solution #4

Environment is an option. Exit(0) and Application.Exit are two methods for exiting a program.

Environment. Exit(): terminates this process and gives the underlying operating system the specified exit code.

Answered by aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

Post is based on