views:

92

answers:

5

If I have a static class with a static field such as:

private static myField = new myObject();

I then have a bunch of static methods that use myField.

Is myField re-instantiated for each method call? My guess is that it's instantiated the first time a method is called that uses it and it remains in memory until the GC clears it up?

Cheers for any pointers :-)

+5  A: 

No, it is assigned to one time, when the class is first accessed. The GC will not release the memory for this instance while the application is running - the memory will be freed when the AppDomain unloads.

Andrew Hare
+1  A: 

There is an article by Jon Skeet about initializing and the beforefieldinit flag. It explains a bit about initializing and quotes the important parts of the C# spec, too.

tanascius
+1  A: 

It is instantitated only once. It is intantiated the moment you use a static method for the first time. You can also instantiate it in the static construtor.

KhanS
A: 

A static field initializer is run once for a given app domain, and the field remains available for the life of the program. The CG will not collect any object that is referenced by a static member variable.

If the class has a static constructor, then the static field initializer is executed just before that constructor, which occurs the first time a static member is referenced or an instance constructor is executed. If there is no static constructor, then the field is initialized at some undetermined time before any static members or instance constructors are executed.

Jeffrey L Whitledge
A: 

It is assigned only once, during class initialization. That happens effectively the first time the class is "actively" touched. See: class initialization in JVM spec for exact details of when the class will be initialized.

Assuming the class this code is in is called MyClass, myField will be GCed shortly after the classloader that loaded MyClass is GCed. (classes get unloaded at classloader granularity in all the major JVMs).

Trent Gray-Donald