Program Entry point in C#

Example 1 & 2

Copy as a command takes two parameters; the source and destination files. Similarly, a C# program can also accept command line parameters at runtime. The executable kamran.exe can be entered as

C:\>kamran one two three

kamran.cs
class zzz
{
  public static void Main(string[] a)
  {
    int i;
    for ( i=0; i< a.Length; i++)
      System.Console.WriteLine(a[i]);
  }
}


Output
one
two
three


one, two, three are called command line parameters. The program accepts them in an array of strings. As the array is a parameter to the function, we are free to decide on its name. Every array has a member called Length, which tells us the size of the array. In our case, it is three. Thus, a[0] will contain the first word one and not the name of the program, a[1] will contain two and a[3] - three. Main now behaves like any other function. What we do next with the command line arguments depends entirely upon us.

kamran.cs
class zzz
{
  public static void Main(string[] a)
  {
  }
  public static int Main()
  {
  }
}


Compiler Error
kamran.cs(3,20): error CS0017: Program 'kamran.exe' has more than one entry point defined: 'zzz.Main(string[])'
kamran.cs(6,19): error CS0017: Program 'kamran.exe' has more than one entry point defined: 'zzz.Main()'


You can have one and only one function called Main in any C# program. Even though you can call it with different parameters, with the name changing, Main as a function must be given only once.

You might also like...

Comments

About the author

Kamran Shakil Pakistan

I am 22 male. BS(Computer Science), MCSE, Brainbench certifed. Member of .NET Open source, Mono Project. E-author on various websites, including www.dotnetextreme.com, www.csharphelp.com and so...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Better train people and risk they leave – than do nothing and risk they stay.” - Anonymous