Click here to Skip to main content
Click here to Skip to main content

Main Method in C#

By , 24 Jan 2013
Rate this:
Please Sign up or sign in to vote.

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.

What is Main() Method and its purpose?

As you see a Program.cs class file create with a default Main() method. This Main() method used to signify the entry point of your application. This Main() method present in every executable C# application. C# executable means any Console application, Windows desktop application or Windows service application.

What if we have more classes with Main() method?

The class that defines the Main() method is termed as Application object. However it is possible that we have more than one class that contain Main() method. So we can set which class Main() method will be used as the entry point via the Startup Object drop down list box, located under the Application tab of the Visual Studio project properties editor.

Why Main() method is static?

Static members are scoped to the class level (rather than the object level) and can thus be invoked without the need to first create a new class instance. A main method is static because it is available to run when your program starts and as it is the entry point of the program it runs without creating an instance of the class.

In other words, static functions exist before a class is instantiated so static is applied to the main entry point (Main method).

What is string[] args in Main method? What is there use?

The string[] args may contain any number of Command line arguments which we want to pass to Main() method.

More about Main() method

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.

Return value of Main() method?

Return value of Main() method is void (indicates no return value) by default. We can change it to one of the following possible signatures.

// int return type, array of strings as the parameter.

static int Main(string[] args)
{
  return 0;
}

static void Main()
{
}

static int Main()
{
  return 0;
}

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.

What is use of return of int value in Main Method?

We can use int return value of the main method to check whether there is an error occurred in the main method. For ex if main method executes successfully then we will return 0 (this is the default value return by the main method even if it defined as void). If main method executes unsuccessfully then we will return -1.

On the Windows operating system, an application’s return value is stored within a system environment variable named %ERRORLEVEL%. An application’s return value is passed to the system at the time the application terminates, it is 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:

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:

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.

Note that MyConsoleApplication is nothing but application name.

Now open VS command prompt and navigate to the folder where our bat file we have just created. Execute the bat file by typing its name and press enter. You will see the output as shown below with message as This application has failed.

Change the return value as 0 in the main method as shown below.

static int Main(string[] args)
{
  Console.WriteLine("***** My First C# App *****");
  Console.WriteLine("Hello World!");
  Console.WriteLine();
  Console.ReadLine();

  return 0;
}

Again run the bat file from command prompt. You will get the message as “This application has succeeded” as shown in the following figure:

How to use Command line arguments in main method?

We can process the command line arguments pass to main method. One of the possible way is using for loop.

static int Main(string[] args)
{

  for(int i = 0; i < args.Length; i++)
  Console.WriteLine("Arg: {0}", args[i]);
  Console.ReadLine();
  return -1;
}

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

  • Pro C# 2010 .NET 4 Platform book by Andrew Troelsen.

History 

  • Written on Oct 19 2012.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

$andesh M Patil
Software Developer (Senior)
India India
Sandesh has a 6 years of total professional experience in a software development. He first handled the computer in his school days when he was in 7th std working on Lotus. In summer vacation, the school authorities allowed him and other students to use the computers for practicing Lotus and playing different games Smile | :) .
 
He has done computer engineering. Currently he is working in Net 4.0 framework. Even though he is using .Net 4.0 framework for development but still he has not got a chance to work with newer technologies like MVC, WCF etc. However he always try to learn these technologies from his end and eagerly waiting for a chance to work with the newer technologies like MVC, WCF and Silverlight etc.

Comments and Discussions

 
SuggestionDo no take others work [modified] PinmemberArhangel Dmitry22-Oct-12 8:33 
GeneralRe: Do no take others work PinmemberSChristmas22-Oct-12 9:47 
GeneralRe: Do no take others work PinmemberArhangel Dmitry22-Oct-12 10:15 
GeneralRe: Do no take others work PinmemberSlacker00726-Oct-12 1:56 
GeneralRe: Do no take others work PinmemberSChristmas26-Oct-12 2:20 
GeneralRe: Do no take others work PinmemberSlacker00726-Oct-12 2:32 
GeneralRe: Do no take others work PinmemberSChristmas26-Oct-12 2:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140415.2 | Last Updated 24 Jan 2013
Article Copyright 2012 by $andesh M Patil
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid