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?
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.
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.
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.
精彩评论