How to make two C# programs work like in Java preventing the multiple entry point errors

Viewed 70

I have two programs, q1.cs and q2.cs. A class is defined inside both of them, and the main method is also there. And when I do dotnet run, I get the error:
Program has more than one entry point defined
In comparison to Java or using Intellij. I could have multiple files having the main method
and could right-click on a file and run it.
Is there something similar available for C# in visual studio code
or any easy alternatives. It seems weird not having this simple functionality.
Does that mean I will have to create a new project every time I want to run a simple program?

1 Answers

Based on this answer:

Having two Main methods is just fine. If you receive the error you mentioned then you need only to tell Visual Studio which one you'd like to use.

Right-click on your project to view the properties. Go to the Application tab and choose the entry point you desire from the Startup object dropdown. Here's an example where I have two entry points depending on how I want to dev-test the assembly.

Application properties

In this window select your desired class containing Main method. Using this method you can have project with more than one class containing Main method.

Doing so sets following node in project's .csproj file

  <PropertyGroup>
    <StartupObject>TrelloMonitor.Console_Looped</StartupObject>
  </PropertyGroup>

In your case, TrelloMonitor.ConsoleLooped is replaced with your selected class namespace and class name. You can edit project's .csproj file directly and set your project's entry point, this file is an XML file.

Another solution is using this command line for building project dotnet build foo.csproj -p:StartupObject=foo.Program, In this case foo.Program specifies main class or project entry point.

Related