2

I've found a few related questions in Java, but none for C#, so please forgive any duplicates.

Short and sweet, whats the difference? Is there any?

public static class Foo
{
    public static List<Bar> Bars;

    static Foo()
    {
        Bars = new List<Bar>();
    }
}

public static class Foo
{
    public static List<Bar> Bars = new List<Bar>();
}

See the comment by @Nick G for the answer to the case of non-static classes. I'd still like to know if it affects static classes any differently.

Now they don't have to be static either. What about this case?

public class Foo
{
    public List<Bar> Bars;

    public Foo()
    {
        Bars = new List<Bar>();
    }
}

public class Foo
{
    public List<Bar> Bars = new List<Bar>();
}

Adam Schiavone
  • 2,412
  • 3
  • 32
  • 65
  • According to [this](http://jonskeet.uk/csharp/constructors.html), the difference is that instance initializers run first, then the constructor runs. The docs for [static field initialization](https://msdn.microsoft.com/en-us/library/aa645758(v=vs.71).aspx) and [instance field initialization](https://msdn.microsoft.com/en-us/library/aa645759(v=vs.71).aspx) both indicate that the fields are initialized before the constructor. Also read [here](https://blogs.msdn.microsoft.com/ericlippert/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-one/) for inheritance info. – Quantic Dec 02 '16 at 19:28
  • 2
    I don't think this answers your static question completely, but may help: http://csharpindepth.com/Articles/General/Beforefieldinit.aspx – Nick G Dec 02 '16 at 19:32
  • 1
    check this [article](http://csharpindepth.com/Articles/General/Beforefieldinit.aspx) there is slight significance to existence of static constructor. – Rafal Dec 02 '16 at 19:37

1 Answers1

1

No, there is not,

According to the IL, static inline initializer uses constructors, see what happened:

1) static inline initializer:

static class SomeClass
{
    public static string strField = "Some String";

    static SomeClass()
    {

    }
}

and the IL:

.method private hidebysig specialname rtspecialname static 
        void  .cctor() cil managed
{
  // Code size       12 (0xc)
  .maxstack  8
  IL_0000:  ldstr      "Some String"
  IL_0005:  stsfld     string forStackoverflow.SomeClass::strField
  IL_000a:  nop
  IL_000b:  ret
} // end of method SomeClass::.cctor

2) constructor:

static class SomeClass
{
    public static string strField;

    static SomeClass()
    {
        strField = "Some String";
    }
}

and the IL:

.method private hidebysig specialname rtspecialname static 
        void  .cctor() cil managed
{
  // Code size       12 (0xc)
  .maxstack  8
  IL_0000:  nop
  IL_0001:  ldstr      "Some String"
  IL_0006:  stsfld     string forStackoverflow.SomeClass::strField
  IL_000b:  ret
} // end of method SomeClass::.cctor

so, from the compiler view-sight, no, there is no difference.

Mehdi Khademloo
  • 2,754
  • 2
  • 20
  • 40