Static constructor does not work for structures

Env .: C # 6, Visual Studio 2015 CTP 6

In the following example:

namespace StaticCTOR { struct SavingsAccount { // static members public static double currInterestRate = 0.04; static SavingsAccount() { currInterestRate = 0.06; Console.WriteLine("static ctor of SavingsAccount"); } // public double Balance; } class Program { static void Main(string[] args) { SavingsAccount s1 = new SavingsAccount(); s1.Balance = 10000; Console.WriteLine("The balance of my account is \{s1.Balance}"); Console.ReadKey(); } } 

}

For some reason, static ctor fails. If I declare SavingsAccount as a class instead of a structure, it works fine.

+6
source share
1 answer

The static constructor is not executed because you are not using any static members of the structure.

If you use the static member currInterestRate , then the static constructor is called first:

 Console.WriteLine(SavingsAccount.currInterestRate); 

Output:

 static ctor of SavingsAccount 0,06 

When you use a class, the static constructor will be called before the instance is created. A constructor call for a structure does not instantiate, so it does not call a static constructor.

+13
source

Source: https://habr.com/ru/post/985818/


All Articles