There is no such thing as C# Static constructor : how to change readonly value without ref

There is no such thing as a C# static type constructor. Rather, C# does support static types initializers, which doesn't bear quite the same semantics.

Consider this fragment:

class Demo
{
  public static void Main(string[] args)
  {
    Console.Out.WriteLine("A.Val = {0}", A.Val);
    Console.Out.WriteLine("B.Val = {0}", B.Val);
  }
}

static class  A
{
  public static readonly int Val;
  static A(){ Val = B.Val + 1; }
}

static class B
{
  public static readonly int Val
  static B() { Val = A.Val + 1; }
}

The result will be...

A.Val = 2
B.Val = 1

If these were constructors, the CLR would throw an exception as the static constructor A is calling static B() which in turns references a field in A that hasn't yet been initialized, but the static class already exists.

No comments:

Post a Comment

Please leave your comments in English or French and I will be pleased to answer them if you have any questions.

Spammers will be walked down the plank matey. Arrr!