Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static constructor not working for structs

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.

like image 922
Bruno Santos Avatar asked Apr 23 '15 20:04

Bruno Santos


People also ask

Can struct have static constructor?

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.

Can structs have Parameterless constructor?

A parameterless instance constructor is valid for all struct kinds including struct , readonly struct , ref struct , and record struct .

Can a struct have a constructor C#?

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.

Why static constructor is Parameterless in C#?

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.


1 Answers

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.

like image 194
Guffa Avatar answered Oct 20 '22 07:10

Guffa