15

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?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
rkg
  • 5,559
  • 8
  • 37
  • 50
  • possible duplicate of [When should one use Environment.Exit to terminate a console application?](http://stackoverflow.com/questions/692323/when-should-one-use-environment-exit-to-terminate-a-console-application) – nawfal Jan 10 '14 at 10:21
  • 2
    Downvoted because the title of this question mentions `Environment.ExitCode`, but the text of the question talks about `Environment.Exit()`. Those are not the same thing. – Dan Jun 22 '16 at 17:36

3 Answers3

17

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.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
7

If you are writing a linear program, then returning from Main is fine. If you've got more complex logic, or possibly other threads of execution then you might want to use Exit(returnCode). Both ways will be equivalent to your shell script.

Tony Casale
  • 1,537
  • 8
  • 7
  • 1
    Except that Environment.Exit() is equivalent to killing the power to the program while it is still running. It should be avoided at all costs, as the next poster states. – debracey Mar 10 '11 at 01:58
1

The difference lies when you need to handle the event on a parent application based on exit status of another application. Return is primarily used within an application, while exit is used to suddenly end an application. Here exit status can be used by another application to decide on its next steps.

A return is used when you are returning a value to another function from where the code is called. or to indicate the end of code execution on some event.

You can also see it like this:

1) A return ends a function, which could be main(); an exit is used to end the program.

2) Ending a program with a certain return value does cannot be interpreted implicitly by another application, but exit status can be used to decide on a code implementation.