Search code examples
c#.netconstructor

What is difference between Static Constructor assignment and Inline-initialize syntax


I want to know what is exactly the benefit of Static Constructor?

In my case, I have a class Test with a static member called Id.

I can set the value to Id as inline syntax:

public class Test
{
    public static int Id = 10;
}

anyway. some article says the static constructor is used for conditional value setting to static members...

So I create a class called Test1 with static member ChildId and ChildId pend for Id value inside the Test class.

As you can see I can conditional value setting as inline syntax:

class Test1
{
    public static int ChildId = Test.Id < 10 ? 20 : 100;
}

what is exactly the benefit of Static Constructor?


Solution

  • There are a few things here:

    1. the order of field initializers can make code brittle if field initializers interact with other fields; the order is top-to-bottom, which means:
      • moving code around can break things
      • when using partial types over multiple files, the order is essentially non-deterministic, making field initializers that rely on fields in other files very unwise
    2. sometimes you need multiple steps to initialize a field, involving temporary variables etc; not everything can be achieved in the single expression allowed by a field initializer (a static method is also a viable option here, if you want multiple steps without triggering beforefieldinit)
    3. static initializers also trigger an IL behavior called beforefieldinit; whether you want this (or even care about this) is contextual, and it is complicated; useful reference