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.
A class or struct can only have one static constructor. Static constructors cannot be inherited or overloaded. A static constructor cannot be called directly and is only meant to be called by the common language runtime (CLR). It is invoked automatically.
A parameterless instance constructor is valid for all struct kinds including struct , readonly struct , ref struct , and record struct .
Unlike a class, a struct is not permitted to declare a parameterless instance constructor. Instead, every struct implicitly has a parameterless instance constructor, which always returns the value that results from setting all fields to their default values.
When a data member is shared among different instances it is imperative that data should be consistent among all the instances of the class. And also there is no way to call static constructor explicitly. Therefore the purpose of having a parameterized static constructor is useless.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With