0

Microsoft docs say the following :

A static constructor is used to initialize any static data

Lets say I have this code :

class Animal
{
    static string name; 


    static Animal()
    {
        Animal.name = "Jack";
    }
}

Is there a difference if I would declare the static name outside of the static constructor like this :

static string name = "Jack"

What is normally done in real world examples ? The first or the latter.

Kevin.a
  • 4,094
  • 8
  • 46
  • 82
  • 3
    [The presence of a static constructor prevents the addition of the BeforeFieldInit type attribute. This limits runtime optimization. A field declared as static readonly may only be assigned as part of its declaration or in a static constructor. When an explicit static constructor is not required, initialize static fields at declaration, rather than through a static constructor for better runtime optimization.](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors). Therefore, prefer the non constructor approach if possible. – CodingYoshi May 12 '20 at 23:24
  • From [static constructors](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors) _If static field variable initializers are present in the class of the static constructor, they will be executed in the textual order in which they appear in the class declaration immediately prior to the execution of the static constructor._ – Pavel Anikhouski May 13 '20 at 06:48

1 Answers1

1

you can always do the later, as long as your static fields don't depend on each other. when they depend on each other, they need to be initialized in order, so it's better to place them in a static constructor

Patrick Beynio
  • 788
  • 1
  • 6
  • 13
  • 3
    The static constructor also plays a part in the lack of `beforefieldinit`. The above example maybe contrived but I'd suggest also looking at this question and answer for further info https://stackoverflow.com/q/610818/491907 – pinkfloydx33 May 12 '20 at 23:25