kiss my armpit
kiss my armpit

Reputation: 3519

What is the difference if I put Main() inside a struct instead of a class?

What is the difference if I put the static method Main() inside a struct instead of a class?

struct Program
{
    static void Main(string[] args)
    {
        System.Console.WriteLine("Hello World");
    }
}

If there is no difference, why did Microsoft choose a class for its container by default?

Upvotes: 1

Views: 74

Answers (2)

Parimal Raj
Parimal Raj

Reputation: 20585

There is NO difference from the Application Statup Point of View.

If you look at the IL codes.

  • In case of struct the program class extends from System.ValueType, while in case of class the program extends from System.Object

For class

.class private auto ansi beforefieldinit Program
    extends [mscorlib]System.Object
{
    .method public hidebysig specialname rtspecialname instance void .ctor() cil managed
    {
        .maxstack 8
        L_0000: ldarg.0 
        L_0001: call instance void [mscorlib]System.Object::.ctor()
        L_0006: ret 
    }

    .method private hidebysig static void Main(string[] args) cil managed
    {
        .maxstack 8
        L_0000: ldstr "Hello World"
        L_0005: call void [mscorlib]System.Console::WriteLine(string)
        L_000a: ret 
    }

}

For struct

.class private sequential ansi sealed beforefieldinit Program
    extends [mscorlib]System.ValueType
{
    .method private hidebysig static void Main(string[] args) cil managed
    {
        .entrypoint
        .maxstack 8
        L_0000: ldstr "Hello World"
        L_0005: call void [mscorlib]System.Console::WriteLine(string)
        L_000a: ret 
    }

}

Upvotes: 0

SLaks
SLaks

Reputation: 887469

There is no difference whatsoever.
(beyond the ordinary differences between structs and classes)

If you don't create any instances of the type, you should put it in a static class.
If you do, you should decide based on the actual usage of the type.

Upvotes: 3

Related Questions