Question

Consider I have

public class ClassA
{
     public string PropertyB { get; set; }
}

And then I use it like this

public class ClassD
{
     static readonly ClassA PropertyE = new ClassA();

     static ClassD()
     {
          PropertyE.PropertyB = "valueF";
     }
}

but the rest of the code didn't work as I expected. Then I rewrote ClassD, and it worked

public class ClassD
{
     static readonly ClassA PropertyE = new ClassA { PropertyB = "valueF" };
}

In which way are these two code samples different? I expected that they had the same behavior, but they don't.

Was it helpful?

Solution

According to MSDN:

If a class contains any static fields with initializers, those initializers are executed in textual order immediately prior to executing the static constructor.

The only difference between your two classes is how PropertyE is initialized. In the first, sample, ClassD.PropertyE is assigned first, then ClassA.PropertyB. In the second sample, ClassA.PropertyB is assigned first, then ClassD.PropertyE. This could produce slightly different results.

You might also have issues with circular dependencies among fields. As the MSDN article states:

It is possible to construct circular dependencies that allow static fields with variable initializers to be observed in their default value state.

using System;
class A
{
   public static int X;
   static A() {
      X = B.Y + 1;
   }
}
class B
{
   public static int Y = A.X + 1;
   static B() {}
   static void Main() {
      Console.WriteLine("X = {0}, Y = {1}", A.X, B.Y);
   }
}

produces the output

X = 1, Y = 2

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top