Main Method in C#: Sandesh M Patil
Main Method in C#: Sandesh M Patil
Introduction
When we create a Console application there is default main method created. I
am always fascinated about why this main method is static void and why the
arguments are supplied by default. I am going to explain this topics in this
article.
Main() Method
So let's start by creating a sample console application. Open your visual studio
framework. File -> New -> Project -> Select Console Application.
By default Visual Studio defines Main() method as private. The reason behind
this other application can not invoke the entry point (Main() method) of another.
However please note that we can declare the Main()method as public.
We can return an int value in main method if we want some output when
program terminates like whether the program completed execution successfully.
Also we can use string[] args parameter in Main() method if we want to process
some user defined command line arguments. We can see this in more detail in
below points.
obviously not possible for an application to obtain and display its final error code
while running.
To capture the return value we have to create a batch file. So lets start creating
a main method as shown below:
Hide Copy Code
static int Main(string[] args)
{
Console.WriteLine("***** My First C# App *****");
Console.WriteLine("Hello World!");
Console.WriteLine();
Console.ReadLine();
return -1;
}
Now navigate to the folder where our application resides. Go to bin folder. Then
go to debug folder. Create a bat file (batch file) and update its content with the
following code:
Hide Copy Code
MyConsoleApplication
@if "%ERRORLEVEL%" == "0" goto success
:fail
echo This application has failed!
echo return value = %ERRORLEVEL%
goto end
:success
echo This application has succeeded!
echo return value = %ERRORLEVEL%
goto end
:end
echo All Done.
Again run the bat file from command prompt. You will get the message as This
application has succeeded as shown in the following figure:
We can pass the arguments using VS command prompt. Just go to the path
where our application resides and execute the application exe by passing the
arguments value as shown in following figure:
During development we can set possible command line arguments for testing
purpose. To do this, right click on project and click on properties. Select Debug
tab and write you command line arguments under the start options section as
shown in the following figure:
So when we run the application, we will get the output as shown in the following
figure.
Summary
In this article we have learned about:
Main method
How to set a particular main method as the entry point of our application?
How to use return value of the main method to show an error.
What the arguments are in main method and how to use them.
Reference