Console App Exit Codes

1 Comment

Console apps can return exit codes to provide a way to show the app has successfully run. Here we will go through an example of creating an exe that returns an exit code.

First, create a new C# console app:

Now, to the main method, we will add:

 static void Main(string[] args)
 {
    Environment.ExitCode = 5;
 }

The Environment.ExitCode will set the exit code value.

To get the output, we will create a new bat file like below:

@echo off
start /wait Carl.ExitCodes.exe
echo %ERRORLEVEL%

Note the %ERRORLEVEL% will read the returned exit code.

Run the app. You will see the exit code of 5 returned:

There is another way to set the exit code. You can set the main method to return an integer and set that integer value:

 static int Main(string[] args)
 {
    return 6;
 }

Output:

Finally, make use of Enum to hold and return the error:

        enum ExitCode : int
        {
            Success = 0,
            Error = 1
        }

        static int Main(string[] args)
        {
            return (int)ExitCode.Success;
        }

 

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

See more articles on: C#

One Response to Console App Exit Codes

  1. Why is it the the ExitCode is always 0 in below code?
    static void Main(string[] args)
    {
    if (args.Length == 1)
    {
    Environment.ExitCode = 1;
    }
    else if (args.Length == 2)
    {
    Environment.ExitCode = 2;
    }
    if (args.Length == 0)
    {
    Environment.ExitCode = 0;
    }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *