C# – How to fix “error CS5001: Program ‘xyz.exe’ does not contain a static ‘Main’ method suitable for an entry point”?

If you want to create an executable file from your ‘C#’ project or file, your code should contain a ‘static Main’ method. This is an entry point to ‘C#’ program. Otherwise, ‘C#’ compiler will throw the below error:

error CS5001: Program 'xyz.exe' does not contain a static 'Main' method suitable for an entry point

To resolve this error, we have two options here.

  • One is, add ‘static Main‘ method into the project or the class.
    • Entry point for standalone ‘C#’ application is it’s ‘Main’ method. ‘static Main‘ method should exist in any one class in ‘C#’ project or file.
  • Other option is, build the project or file as a library (DLL – Dynamic Link Library).
    • These type of files are not self-executable. DLL files will be used into other assemblies or applications. So, for these file, ‘Main’ entry point is not required.

That said, depending on the requirement, we can create a self executable file or a DLL from the ‘C#’ code file or project.

Let’s take a simple example to produce the error and discuss about the steps to resolve the issue.

// Sample.cs
public class Sample
{
    public void Display()
    {
        System.Console.WriteLine("Hello, World!");
    }
};

When we compile above program; ‘C#’ compiler will throw below error:

c:\>csc Sample.cs
Microsoft (R) Visual C# Compiler version 4.0.30319.17929
for Microsoft (R) .NET Framework 4.5
Copyright (C) Microsoft Corporation. All rights reserved.

error CS5001: Program 'c:\Sample.exe'
        does not contain a static 'Main' method suitable for an entry point

As we mentioned above, we have two ways to resolve this problem. Lets try to resolve this without modifying any code.

Compile the above program “Sample.cs” as a target library instead of an executable. Below is the command:

c:\>csc /target:library Sample.cs
Microsoft (R) Visual C# Compiler version 4.0.30319.17929
for Microsoft (R) .NET Framework 4.5
Copyright (C) Microsoft Corporation. All rights reserved.

Observe that 'C#' compiler successfully compiled the program and generates "Sample.dll" file.

Another way to resolve this error is, by adding the ‘static Main’ method. ‘Main’ method should be added into the ‘Sample’ class as a static method. After adding the ‘Main’ method above code looks like below.

// Sample.cs
public class Sample
{
    public void Display()
    {
        System.Console.WriteLine("Hello, World!");
    }

    static void Main()
    {
    }
};

Now compile this program and observe that ‘C#’ compiler successfully compiled the program and generates “Sample.exe” file. Below is the command to compile above code:

csc basic.cs

We can choose any one of these methods, depending on our requirements, to resolve this issue “error CS5001”.

(Raju)

One Comment

Add a Comment

Your email address will not be published.