0

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.

2
  • 1
    What exactly didn't work after the first example? Maybe the cause isn't found here but rather a result of something you left behind (per @p.s.w.g's comment) Commented Aug 7, 2013 at 22:18
  • 1
    You need to expand upon but the rest of the code didn't work as I expected with emphasis on what you expected (I expected that they had the same behavior, but they don't). Commented Aug 7, 2013 at 22:31

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

6 Comments

If this was the case, the two code samples would have the same behavior, wouldn't they?
@JaderDias Can you explain how they behave differently?
The behavior was the same as if the static constructor wasn't executed at all.
@JaderDias I tried a sample app using your code with slight modifications (this. not valid in static constructor, PropertyE made public, and valueF replace with a string constant "valueF". I got exactly what you would expect: Console.WriteLine(ClassD.PropertyE.PropertyB); // valueF
@JaderDias not when it comes to the order of initialization.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.