13
votes

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?
8

8 Answers

16
votes

You can use either int or void as a return type. Thus, simply change it and return a value like in C++.

Maybe it's void by default in order not to puzzle beginners.

12
votes

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);

7
votes

It's not implicitly void. As in, you can't just declare main(String[] args) and have it compile as a void function. The default projects declare main() as void because the default projects don't have anything useful to return from main.

It's also worth noting that C# is not C or C++. Some of the syntax is the same, but the differences are far vaster.

6
votes

The reasons behind why C#'s developers decided to have Main declared as void I couldn't say. As far as returning values to the OS when the application has finished you can use this:

System.Environment.ExitCode = 1; // Or whatever number other than 0 for errors.
3
votes

You can change the return type of Main without causing any problems.

2
votes

Remember, that there is still another "box" around your program - the CLR. It will return error codes, when your code throws an unhandled exception.

2
votes

Best way to return an exit value is to use. I say this because non-zero exit codes are usually used to signify some error, typically one that you wouldn't want to continue from. Calling Exit with a non-zero exit value both signals the error through the value and exits the program.

Environment.Exit( value );

EDIT: Note, the context for my statement was within Main for a console program. Libraries and other methods should throw exceptions or return error values. Only your main routine should call Exit. Sorry if this wasn't clear.

0
votes

You can use Environment.Exit() to terminate and return an integer code to the OS. Alternatively, you can set Environment.ExitCode and that code will be returned to the OS whenever your program terminates normally.