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

If we want to create an executable from your ‘C#’ project or file, our code should contain a ‘static Main’ method. This is the entry point to ‘C#’ program. If our code missed this, ‘C#’ 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, we have two options here.

  • One is, add ‘static Main’ method into the project or the class.
    • Entry point for standalone ‘C#’ application is its ‘Main’ method. ‘static Main’ method should exist in any one class in ‘C#’ project or file.
  • 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.

Lets 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

c:\>

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.

c:\>

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

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

Leave a Reply