What is the preferred way to exit the command line?

It should be easy. I just need to just exit my C # command-line program - no fancy stuff.

Should i use

Environment.Exit(); 

or

 this.Close(); 

or something else?

+8
command-line c #
source share
2 answers

Use return; in your Main method.
If you are not in the main method, when you decide to exit the program, you need to return from the method that is currently being executed by the main method.

Example:

 void Main(...) { DisplayAvailableCommands(); ProcessCommands(); } void ProcessCommands() { while(true) { var command = ReadCommandFromConsole(); switch(command) { case "help": DisplayHelp(); break; case "exit": return; } } } 

This is actually not an example of a good overall console application design, but it illustrates the point.

+11
source share

just return from the Main method.

Edit:

if you really lost the thread and want to exit from anywhere in the application (for example, inside any method called Main), you can use:

 Environment.Exit(0); 

remember that usually you should return 0 to the calling process (OS) when everything is fine, and you will return a non-zero value if an error occurs and the execution does not turn out as smooth as it should be.

+14
source share

All Articles