Reputation: 735
Env.: C#6, Visual Studio 2015 CTP 6
Given 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();
}
}
}
The static ctor is not being executed for some reason. If I declare SavingsAccount as a class instead of a struct, it works just fine.
Upvotes: 9
Views: 2874
Reputation: 1484
According to the CLI spec:
If not marked BeforeFieldInit then that type’s initializer method is executed at (i.e., is triggered by):
- first access to any static field of that type, or
- first invocation of any static method of that type, or
- first invocation of any instance or virtual method of that type if it is a value type or
- first invocation of any constructor for that type
For structs which have an implicit default constructor it is not actually invoked, so you can create an instance and access its fields. Everything else (invoking custom constructors, instance property access, method calls, static field access) will trigger static constructor invocation.
Also note that invoking inherited Object
methods which are not overridden in the struct (e.g. ToString()
) will not trigger static constructor invocation.
Upvotes: 0
Reputation: 700720
The static constructor isn't executed because you are not using any static members of the struct.
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 are using a class, the static constructor will be called before the instance is created. Calling a constructor for a structure doesn't create an instance, so it doesn't trigger the static constructor.
Upvotes: 13