37

I was wondering about when does a static variable(in a class) come into picture(initialized)? Is it after the instance constructor called for the first time or after the class loads? When does a class loading occur?

2

2 Answers 2

42

Oh, that is complex. It depends on whether the beforefieldinit flag is set, which in turn (in C#) depends on whether there is a static constructor. And worse; in .NET 4 I believe the behaviour changed to make it more "lazy" than it used to be.

Frankly, I wouldn't code to any specific behaviour here; simply: static fields will be initialized before you try to use them, as long as you use regular code to access them.

Jon Skeet has a good write-up on this here

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

Comments

2

Static variables comes into picture after the corresponding class loading. It is not after constructor calling, because constructor calling comes into play when we are using new operator to create object of class and static variables are available on class level not on object level.

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.