1

I am developing a .NET Console Application and keep seeing where another developer has used Environment.ExitCode = -1; in their catch statements. I have read the answer here and was satisfied to discover

You can set the exit code using properties: Environment.ExitCode = -1;. This will be used if nothing else sets the return code or uses one of the other options above).

Again the link I have placed above is not the same question this is a question regarding method usage not about how to set the code.

To my understanding this is stating that if no other exit code has been provided and no other exit method is given -1 is used. If I am wrong on that assumption it would be great to get clarification.

Which leaves me with wondering if this would be the same as calling Environment.Exit(-1);? In both cases the ExitCode is being set to -1 to be reported to the operating system. Is reporting it directly by calling Environment.Exit(-1); undermining the ability of Environment.ExitCode = -1;?

1 Answers1

2

Environment.Exit(-1) terminates the process and sends an exit code of -1 to the operating system. Environment.ExitCode = -1 does not terminate the process, but sets the exit code to -1 for when the process terminates.

I found this information here and here.

So here's an example of the difference in usage:

public class ExitCodeUsage
{
   public static void Main()
   {
      string[] args = Environment.GetCommandLineArgs();
      if (args.Length == 1) {
         Environment.ExitCode = -1;  
      }
      else {
         //Do stuff that requires the length of args to be not equal to 1.
      }
   }
}
public class ExitUsage
{
   public static void Main()
   {
      string[] args = Environment.GetCommandLineArgs();
      if (args.Length == 1) {
         Environment.Exit(-1);  
      }

      //Do stuff that requires the length of args to be not equal to 1.

   }
}
DutchJelly
  • 116
  • 9
  • So setting it is essentially waiting for something else to set an exit code and if not then whatever it is set to is returned? – NetPenguin21 Jul 10 '19 at 19:10
  • Setting it is basically setting the exit code for the time being. When your program stops it'll send the most recent code you set the exit code to, to your operating system. Environment.Exit(-1) does the same, but stops your program so -1 will be the most recent version of the exit code, which will be sent to your operating system. – DutchJelly Jul 10 '19 at 19:14
  • Thanks so it is just a matter of waiting for "finishing up" to occur versus hard stop. So is -1 just a choice of that developer or does this int have some kind of significance? (Significance in terms of all environments not just the meaning that developer put on it) – NetPenguin21 Jul 10 '19 at 19:16