2

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.

8
  • 1
    unlikely to be actual answer, but there could be a static constructor that sets it back to null (i.e. a developer was just being mean). Also, in the future could you please provide code snippets as text, not as pictures of text? Commented Jul 23, 2012 at 18:19
  • Why not check s_Law in the getter and set it to a new instance if it is null? Commented Jul 23, 2012 at 18:21
  • @mgnoonan Well, it's readonly, so you couldn't set it if you tried. Beyond that; the point is that it should never be null because it's initialized to a value and can't be changed afterwards. Commented Jul 23, 2012 at 18:23
  • 2
    Is there an error being thrown in the LawClass constructor? Commented Jul 23, 2012 at 18:26
  • 3
    Unable to reproduce. Only thing I can think of is that there is an unshown [ThreadStatic] attribute above the readonly field, and that the instance is created from one thread, and the get is called from another thread. Static initializations are only done once. Commented Jul 23, 2012 at 18:29

2 Answers 2

4

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.

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

1 Comment

Where you have currently broken, the line of code requiring the defined value of s_Law isn't yet needed. On the next line, a value will be required and I would expect the initialization to occur at that time. Statics aren't required to be lazy, but in the Microsoft CLR they usually are.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.