Search code examples
c#classstructentry-point

Is there a difference between Main() in a structure versus a class?


Let's say in C# I had my Main() function in an Entry class that exists solely to house the entry-point. I would do it like such:

public class Entry
{

    public static void Main()
    {

        ...

    }

}

I consider this pretty typical, and at least in some Java projects at work I have seen classes exist just for the main() function and never thought twice about it. But while I have been learning more about C# and structures, I tried to do the following:

public struct Entry
{

    public static void Main()
    {

        ...

    }

}

and it worked exactly the same visually. So, assuming that your entry point in C# contains only your Main() function, does making it's container a struct have any actual difference compared to a class at runtime?


Solution

  • The answer is, in regards to an entry-point (and your constraints) there is no appreciable difference apart from a few bytes here and there. However, let's visit the documentation:

    Main() and command-line arguments (C# Programming Guide)

    The Main method is the entry point of a C# application. (Libraries and services do not require a Main method as an entry point.) When the application is started, the Main method is the first method that is invoked.

    Overview

    • The Main method is the entry point of an executable program; it is where the program control starts and ends.
    • Main is declared inside a class or struct. Main must be static and it need not be public. (In the earlier example, it receives the default access of private.) The enclosing class or struct is not required to be static.

    ...