Referencing multiple projects with top-level statements

Ernest 1 Reputation point
2023-01-30T16:34:45.33+00:00

I have two projects A and B. Each project has a single top-level statement Program.cs file. I made the Program class visible from each project by enabling internals:

<InternalsVisibleTo Include="MyTargetProject" />

The problem is that trying to reference Program class in the target project that has references to both A and B results in a compiler error:

The type 'Program' exists in both 'A, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' and 'B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'

Trying to define Program class by the namespace (project name) doesn't work. As far as I understand, by default, the compiler doesn't generate a namespace for a top-level class. Is there a way to specify a namespace for a top-level statement file?

I'm aware that a workaround would be to convert at least one Program.cs to a "classic" class with a namespace declaration and the Main method as its entry point. However, I would like to avoid doing it and continue using top-level statements if it's possible. Is there any way to achieve this?

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,370 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,238 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 55,686 Reputation points
    2023-01-30T16:47:49.4833333+00:00

    the namespaces are not the issue. when an exe is built, there can only be one declared entry point. one of the projects should be a library, or they should not reference each other.