#8 – The Main() Function Can Return an int
June 25, 2010 7 Comments
Instead of returning void, Main() can return an integer value, which can then be read by the calling program or script. Notice that the return type of the function is an int
class Program { static int Main() { Console.WriteLine("Doing something.."); if (DateTime.Today.DayOfWeek == DayOfWeek.Monday) return -1; // Monday is bad else return 0; } }
I did not understand the code
return -1; // Monday is bad
else
return 0;
can u tell me what does it do ???
This example returns a -1 to the calling program if it is run on Monday, 0 otherwise. A value of 0 is often considered as “success” or “normal”, whereas a negative number is considered as an error. Whatever script or program invoked this application could then check the application’s return value.
How could i check what is the return value is??
when i debug..its doesnt give any info ..
How you check it depends on how you invoke your program. If you call your program from a DOS batch file, you can use the ERRORLEVEL environment variable. If you launch your application from code, the API that you use to launch it should have the ability to retrieve the return value of the application that you launch. If you launch it from Windows Explorer, e.g. as a user, the return value is not reported. If you’re only debugging your program by having the debugger launch your program, it won’t show the return value of the program because the debugger has already terminated the session by the time the value is available.
If you invoke an executable from another C# application, you are able to inspect the return values and respond accordingly.
Can you please let know, on putting where console.Readkey() in this program wil show the return value as when i put it after console.writeline it only prints the sentence but doesn’t shows return value …
Well, you could add a Write that display the value you were about to return, followed by a read so that the console paused. Just make sure to put both before the return statement(s) so that they are displayed before the program exits.