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
?
There are a few things here:
partial
types over multiple files, the order is essentially non-deterministic, making field initializers that rely on fields in other files very unwisestatic
method is also a viable option here, if you want multiple steps without triggering beforefieldinit
)beforefieldinit
; whether you want this (or even care about this) is contextual, and it is complicated; useful reference