loading...

The Main Method in C#

thedotnetweekly profile image The DotNET Weekly ・2 min read

The Main() method is the standard entry point to the execution for any C# program. Libraries and services do not require the Main method as an entry point, this would be required if your application is a console or a windows application.

The following is a list of valid Main signatures:

public static void Main() { }
public static int Main() { }
public static void Main(string[] args) { }
public static int Main(string[] args) { }
public static async Task Main() { }
public static async Task<int> Main() { }
public static async Task Main(string[] args) { }
public static async Task<int> Main(string[] args) { }

When you create a new program using Visual Studio. It would create a Program.cs file with the following definition -

namespace devtodemo
{
    internal class Program
    {
        public static void Main(string[] args)
        {
        }
    }
}

Let's try to understand the reason behind each part of this main method,

  • public: It is not required for this method to be public, it can be protected and even private. If you need to call this method from another class or assemblies then you would make it public. Another use case to make it public is if you want your Unit Tests to call and test this method.

  • static: The Main() method must be static because it is a class-level method, which should be able to call without creating an instance of that class.

  • void: It is the return type of the method, void means the method will not return anything. It can also be of type int or, starting with C# 7.1, Task, or Task return type.

  • Main(): It is the configured name for the Main method. If you do not have this method in your application and you if you try to build your application you would get this error - Program does not contain a static 'Main' method suitable for an entry point

  • String []args : Command line arguments in C#. It allows the user to pass in extra information, to change the way the application behaves. It is an optional parameter.

Let me know in the comments section if you found this useful :)

Follow me on https://www.instagram.com/thedotnetweekly for more such posts.

Posted on by:

thedotnetweekly profile

The DotNET Weekly

@thedotnetweekly

Bi-Weekly posts about dotnet.

Discussion

markdown guide