Several options, by order of most appropriate way:
- Return an int from the Program.Main method
- Throw an exception and don't handle it anywhere (use for unexpected error situations)
- To force termination elsewhere,
System.Environment.Exit (not portable! see below)
Edited 9/2013 to improve readability
Returning with a specific exit code: As Servy points out in the comments, you can declare Main with an
int return type and return an error code that way. So there really is no need to use Environment.Exit unless you need to terminate with an exit code and can't possibly do it in the Main method. Most probably you can avoid that by throwing an exception, and returning an error code in Main if any unhandled exception propagates there. If the application is multi-threaded you'll probably need even more boilerplate to properly terminate with an exit code so you may be better off just calling Environment.Exit.
Another point against using
Evironment.Exit - even when writing multi-threaded applications - is reusability. If you ever want to reuse your code in an environment that makes
Environment.Exit irrelevant (such as a library that may be used in a web server), the code will not be portable. The best solution still is, in my opinion, to always use exceptions and/or return values that represent that the method reached some error/finish state. That way, you can always use the same code in any .NET environment, and in any type of application. If you are writing specifically an app that needs to return an exit code or to terminate in a way similar to what
Environment.Exit does, you can then go ahead and wrap the thread at the highest level and handle the errors/exceptions as needed.