Search code examples
c#.netstandards

Why does C# use implicit void Main?


I don't understand why C#'s Main function is void by default (in a console project for example). In C and C++ the standard clearly says main must return int, and using a return value makes sense because we can check that return value from an external program and see if the C/C++ application finished successfully or encountered an error.

So my questions are:

  1. Why does Visual Studio declare Main as void?
  2. What's the best way of returning a value to the OS once a C# console application has finished executing?

Solution

  • In C#, you can use, see MSDN :

     static int Main() 
     static int Main(string[] args)
     static void Main() 
     static void Main(string[] args)
    

    You can also return a (int) value in 2 ways.

    In a Console application I would use int Main() { ...; return 2; }

    In a WinForms/WPF/... app, in the rare situation it needs a return value, I would use
    Environment.ExitCode = 1; or Environment.Exit(1);