S1118 (Utility classes should not have public constructors) should ignore Program

Language: C#
Rule: S1118
SonarQube Cloud

  • Why do you believe it’s a false-positive/false-negative?

I have an Azure WebApp that I test using WebApplicationFactory<Program>. Program cannot be made static (since it’s used as type argument), and there’s no reason why I should make it private (or internal + visible to my test assembly)

  • How can we reproduce the problem? Give us a self-contained snippet of code (formatted text, no screenshots)
public sealed class Program
{
    public static void Main(string[] args)
    {
        DefaultAzureCredential runtimeAzureCredentials = new();
        
        WebApplicationBuilder builder = CreateWebApplicationBuilder(args);
        WebApplication app = builder.Build();
        app.Run();
    }
...
}

in my tests:

public abstract class IntegrationTestBase: IAsyncDisposable
{
    protected WebApplicationFactory<Program> Factory { get; }
...
}

This can be solved by doing the following:

public sealed class Program
{
    private Program() { }

    public static void Main(string[] args)
    {
        DefaultAzureCredential runtimeAzureCredentials = new();
        
        WebApplicationBuilder builder = CreateWebApplicationBuilder(args);
        WebApplication app = builder.Build();
        app.Run();
    }
...
}

Hello,

we looked into this issue and we consider this a an edge case. There is a language proposal to remove CS0718 which would allow making Program a static class. This would solve your problem. In the meantime you can use the workaround proposed by @Corniel (adding private Program() { }) or suppress the issue via one of the built-in issue suppression mechanisms.

If you think that this isn’t sufficient or there are more reasons why the entry point class should be excluded, just let us know and we will revisit the issue.

Best Martin

1 Like