Should Program class be static?

Viewed 4117

I am getting the following Warning in Visual Studio 2019, after creating a new ASP.NET Core 3 project:

Warning CA1052 Type 'Program' is a static holder type but is neither static nor NotInheritable

public class Program
    {
        public static void Main(string[] args)
        {
            // ...
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            // ...
    }

vs

public static class Program
    {
        public static void Main(string[] args)
        {
            // ...
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            // ...
    }

Should I add the static modifier? Why / Why not? Pro's and Cons'?

Edit: This is a ASP.NET Core 3 API

1 Answers

In more basic terms the message could be imagined to say:

Your class 'Program' only seems to contain methods that are declared as static and as a result it can not participate in an inheritance hierarchy. Declare it as static (or sealed if you're targeting an ancient version of .net that doesn't support static classes) to more accurately reflect what its design sentiment is

It's a recommendation, to mark your class as static because it only contains static stuff. This will prevent anyone making the mistake of trying to inherit from it and thinking they can then do something useful inheritance-wise with the inherited version

Microsoft don't mark it as static for you because there's nothing special about Program per se; you could put non static methods in it, or your could put your static void Main in another class, like Person, that IS instantiable.

class Person{
  public string Name {get;set;}
  static void Main(){
    Person p = new Person();
    p.Name = Console.ReadLine();
  }
}

This would work fine; a class does not have to be static to host the application entry point and in this case the class couldn't be static because it has non static members. It can be (and is, in the main) instantiated in the main. It's not called Program; there isn't a class called Program anywhere and this tiny app will still run (doesn't do much..)

In your case, either do as recommended and add a static modifier to your class, because it will make your program that bit more robustly engineered, or add an instance member if you can think of a valid reason for instantiating Program, or ignore the message and carry on with your non static class that contains only static methods - it'll still work

Related