Search code examples
c#asp.net-coretoplevel-statement

Will adding a namespace and a Main method to Program.cs in ASP.NET Core 6 have any negative effects?


I have an ASP.NET Core 6 Web Api application.

Currently, the Program.cs uses the new program style with top-level statements as described here. This means that it does not have a namespace.

There is a bug in SonarQube 9.3 which raises an error on this point. This bug has been fixed with version 9.6, but it will take time until we update the version at our side.

Therefore, I need a temporary solution so avoid SonarQube errors.

I am thinking of converting Program.cs to the old coding style.

namespace Aa;

public partial class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        //Add services , etc - the whole content of Program.cs
    }
}

I see here that in a console application they are equivalent.

My question is: what about Web API? Can I safely add a namespace and a Main method in an ASP.NET Core 6 Web API? Will there be any side effects?


Solution

  • To minimize side-effects, just copy your top-level statements into a Main method declared in a namespace scope like this:

    namespace foo
    {
        class Program
        {
            public static int Main()
            {
                //top level statements here
                return 0;
            }
        }
    }
    

    Then any other types declared in your Program.cs will remain in the global namespace. In any case possible consequences are limited to compilation errors from moving types to a different namespace.