1

I've read about different ways to set the exit code for a .NET console application here and here and at other places. And they all result in the correct value in the %ERRORLEVEL% after executing the console app from within a cmd.exe (or in $LastExitCode when executing from within powershell) on windows.

However, when i create a simple C# or VB.NET console application and run it from the debugger, the exit code listed in the debugger output window is always zero unless, instead of using return, Environment.Exit(Int32) or Environment.ExitCode are used or when the Visual Studio hosting process is disabled in the project options.

The debug output from both,

namespace TestDotNetConsoleAppExitCode
{
    class Program
    {
        static int Main(string[] args)
        {
            return -3;
        }
    }
}

and

Module Module1
    Function Main() As Integer
        Return -3
    End Function
End Module

results in

The program '[...] ....vshost.exe' has exited with code 0 (0x0).

This happens at least on Win10 and in VS2010 and VS2015 with all .NET frameworks from 2.0 to 4.7.2, but not with .NET Core (there's no vshost there).

Is there some project or visual studio option i'm missing?

wonko realtime
  • 545
  • 9
  • 26
  • 1
    I suspect that's due to the VS debugger hosting. Does the exit code particularly matter to you when running from the debugger? If you just run the process normally, I expect it will exit with the expected code. – Jon Skeet Feb 21 '19 at 10:33
  • @JonSkeet It's just easier to see the exit code after running the debugger. And replacing all return with Environment.Exit(...) has the not so nice sideeffect that scopes are different and several uninitialized variables cause CS0165 to be reported. I could add a return; after each Environment.Exit() but it's annoying. – wonko realtime Feb 21 '19 at 10:42
  • This doesn't happen for me with VS2017. Maybe it's time to upgrade? – Jon Skeet Feb 21 '19 at 10:50
  • 2
    The hosting process option was discontinued in VS2017. There is no practical reason to avoid turning it off with Project > Properties > Debug. – Hans Passant Feb 21 '19 at 11:17
  • Your should take a look at [this](https://stackoverflow.com/a/30780580/9364460) answer which got all the infos. The best 'solution' i can come up with is using the [preprocessor directives](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-if). Something like this: `#if DEBUG Environment.ExitCode = errorCode #endif return errorCode;` – Hyarus Feb 21 '19 at 13:29

0 Answers0