SiberianGuy
SiberianGuy

Reputation: 25292

Static variables initialization order

I have put breakpoint into "get"

static readonly LawClass s_Law = new LawClass();
public static LawClass Law { get { return s_Law; } }

and found out s_law is null.

How is it possible? I thought static variables are initialized before first class access and in line-by-line order.

Upvotes: 2

Views: 229

Answers (2)

SiberianGuy
SiberianGuy

Reputation: 25292

Thank you guys for help! I looked at stack trace and found out I had some crazy recursion in my static variables initialization order. So I simplified the code and now it works.

Upvotes: 0

Nate Kohl
Nate Kohl

Reputation: 35914

This is just a guess, but from http://msdn.microsoft.com/en-us/library/aa645758(v=vs.71).aspx:

If a static constructor (Section 10.11) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.

If you break on the property getter, the static backing field hasn't been accessed yet, and therefore might or might not have been initialized.

Upvotes: 4

Related Questions