-2

I know that the Main method can either return an int or be void. if I use the following Main method signature and run some sort of a code the command-line says "exited with code 0"

 static void Main() {}

if I use the following signature:

static int Main() {
//and let's say return a 5
return 5;
}

It says "exited with code 5"

So my question is:

why does a void signature return a 0 if It is supposed to be void?

Erik_JI
  • 287
  • 1
  • 7
  • 1
    Every process returns a code to the OS when it is done. 0 means everything is OK. other values indicate errors. So in case your `main` does not return anything (void), the default of 0 is actually returned by the process, assuming everything is OK. If `main` returns an `int`, this will be the code returned by the process. – wohlstad Jun 13 '22 at 16:40

1 Answers1

0

You are printing the exit code to the command line. Your process will always exit with an exit code, which will usually be the default value 0 (success). You can specify a different value (e.g. by returning a non-zero value, or setting Environment.ExitCode to a non-zero value). It will also be set to a non-zero (probably large negative) value if your code throws an unhandled exception.

The static int Main() form of the main method allows you to specify that exit code with the return value of Main.

If you use the static void Main() form instead, you cannot specify the exit code of your process with the return value, but it will still have an exit code. You can still explicitly set the exit code using Environment.ExitCode.

pmcoltrane
  • 3,052
  • 1
  • 24
  • 30
  • FYI: "Your process will always exit with an exit code" is not quite true, if Main throws exception the exit code would be large negative value. – Alexei Levenkov Jun 13 '22 at 17:01