How to terminate a .NET console application with an exit code

It happens that you’d like to terminate a .NET console application with some exit code. Normally exit codes are integers where negative numbers indicate that something has gone wrong with -1 being the most common. Positive digits and zero on the other hand usually imply a program execution with no errors. The most common positive exit codes are 0 and 1.

The Environment object has a method called Exit that accepts an integer as the exit code:

static void Main(string[] args)
{
    Environment.Exit(-1);
}

That’s all you need if you’d like to terminate a .NET console application with some exit code.

View all various C# language feature related posts here.

Unknown's avatarAbout Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

One Response to How to terminate a .NET console application with an exit code

  1. Pail Writer's avatar Pail Writer says:

    Thanks so much for sharing this tip. I am kind-of new to C# and was trying to figure out how I could cleanly exit an app if one of my methods/classes failed. Like usual, I was overthinking this.

    (Sometimes, the easiest way to meet someone is to simply say hello!)

Leave a comment

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

ARCHIVED: Bite-size insight on Cyber Security for the not too technical.