1

Suppose I have a console app containing two CS files:

Program1.cs

using System;

namespace MyConsoleApp
{
    class Program1
    {
        pubic static void Main()
        {
            Console.WriteLine("From Program1");
        }
    }
}

Program2.cs

using System;

namespace MyConsoleApp
{
    class Program2
    {
        pubic static void Main()
        {
            Console.WriteLine("From Program2");
        }
    }
}

If I try to run this app using the dotnet CLI (dotnet run) I'm going to get an error:

error CS0017: Program has more than one entry point defined. Compile with /main to specify the type that contains the entry point

As far as I know, /main is only a flag to csc and not to msbuild. In order to pinpoint the startup type with msbuild one must specify it in the CSPROJ file as MainEntryPoint or StartupObject.

In my case, I'd like to be able to specify this on the fly through the dotnet CLI. Unfortunately the following still throws the exact same error:

dotnet run msbuild /main:MyConsoleApp.Program1

How do I pass csc's /main switch to msbuild through the dotnet CLI?

Edit

This is not a duplicate because the /p switch doesn't help:

$ dotnet build /p:StartupObject=MyConsoleApp.Program2
Microsoft (R) Build Engine version 16.11.3+5d7fe36cf for .NET
Copyright (C) Microsoft Corporation. All rights reserved.

  Determining projects to restore...
  Restored C:\Users\MyConsoleApp\MyConsoleApp.csproj (in 86 ms).
  MyConsoleApp -> C:\Users\MyConsoleApp\bin\Debug\netcoreapp3.1\MyConsoleApp.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:01.76
$ dotnet run
From Program1
user32882
  • 5,094
  • 5
  • 43
  • 82
  • Does this answer your question? [How can I pass a parameter through MSBuild to the compiler?](https://stackoverflow.com/questions/3063426/how-can-i-pass-a-parameter-through-msbuild-to-the-compiler) – Eldar Oct 05 '22 at 08:34
  • @Eldar not really. I've found that neither `dotnet build` nor `dotnet run` are sensitive to the `/p:StartupObject` switch. – user32882 Oct 05 '22 at 08:51
  • If you are using Net 6.0 `dotnet run doesn't respect arguments like /property:property=value, which are respected by dotnet build.` – Eldar Oct 05 '22 at 09:04
  • By the way `/p` is short form of `/project` not `/property` – Eldar Oct 05 '22 at 09:05
  • I am curios, why do you need two entry points? – Siraf Oct 05 '22 at 09:52

1 Answers1

1

The p switch only works with dotnet build and not dotnet run which is a shame. Also you need to clean the solution before building with the /p switch every time so it picks the right startup object:

dotnet clean --nologo -v=q
dotnet build -v=q /property:StartupObject=MyConsoleApp.Program2
dotnet run

It would be so much nicer if I could just do something like:

dotnet run /p:StartupObject=MyConsoleApp.Program2

user32882
  • 5,094
  • 5
  • 43
  • 82