Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Environment.ExitCode versus returning int from Main

Tags:

c#

exit-code

I am planning to use the return code of the C# executable in one of my shell script. I have two options:

Returning a int value from the main method

class MainReturnValTest
{
    static int Main()
    {
        //...
        return 0;
    }
}

(OR)

Using Environment.Exit with an exit code

class MainReturnValTest
{
    static void Main()
    {
        //...
        Enviroment.Exit(exitCode);
    }
}

Is it fine to use any of the above ways to return value from the executable? Or is one of them preferred over other?

like image 660
rkg Avatar asked Mar 09 '11 22:03

rkg


People also ask

What does Environment exit do c#?

Exit terminates an application immediately, even if other threads are running. If the return statement is called in the application entry point, it causes an application to terminate only after all foreground threads have terminated. Exit requires the caller to have permission to call unmanaged code.

What does Environment exit 0 do?

The exit code to return to the operating system. Use 0 (zero) to indicate that the process completed successfully.


1 Answers

Environment.Exit() is a rude abort. It instantly terminates the process. Use it only when you detect a gross failure, it is appropriate in an AppDomain.UnhandledException event handler for example. Which runs when your program is about to terminate because of an unhandled exception.

Which is your lead: exceptions are a good way to signal unusual conditions that should terminate the program with an ExitCode that isn't zero. In fact, it automatically gets set to the HResult property value of the exception. No code required.

like image 175
Hans Passant Avatar answered Sep 21 '22 10:09

Hans Passant