Static constructor not working for structs
Asked Answered
I

2

9

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.

Included answered 23/4, 2015 at 20:7 Comment(1)
Check out this link on how to setup parameterless constructors in structs.Lacrosse
S
13

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.

Snead answered 23/4, 2015 at 20:14 Comment(2)
@vcsjones Which static member does instantiating an instance use in the example?Cogan
@Cogan ah crap, I was reading the section on static classes. I meant to quote the part that said, "The execution of a static constructor is triggered by the first of the following events to occur within an application domain: An instance of the class is created." but this isn't a class.Raimund
D
0

According to the CLI spec:

If not marked BeforeFieldInit then that type’s initializer method is executed at (i.e., is triggered by):

  1. first access to any static field of that type, or
  2. first invocation of any static method of that type, or
  3. first invocation of any instance or virtual method of that type if it is a value type or
  4. 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.

Dittmer answered 15/1, 2020 at 14:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.