How exactly do static fields work internally?

C#JavaPhpOopStatic Members

C# Problem Overview


Say you have a class,

class Foo
{
    public static bar;
}

When you say:

new Foo();

I can imagine that in memory, a space is reserved for this object.

...and when you say again:

new Foo(); 

...well now you have another space available for the object.

However, where exactly does the static field live?

What I am really trying to learn is:

How do the references to the objects reference the same field of the objects they reference?

C# Solutions


Solution 1 - C#

While the exact details of the type system are implementation dependent, let me go into some more detail than just stating that it depends and you should not care. I'll describe how it approximately works in Microsoft's implementation (.NET) according to the book CLR via C# by Jeffrey Richter and the article See How the CLR Creates Runtime Objects by Hanu Kommalapati et al. (original MSDN May 2005 issue).


Say you have a class:

class Foo
{
	// Instance fields
	string myBar = "Foobar";
	int myNum;
	
	// Static fields
	static string bar = "Foobar";
	static int num;
}

Foo myFoo = new Foo();
Type typeOfFoo = typeof(Foo);

Where do the instance fields live?

Whenever you say new Foo(), space is allocated and initialized for the object instance, and the constructor is called. This instance is shown as instance of Foo in the image below. Such as instance contains only the instance fields of the class (in this case myBar and myNum), and for objects allocated on the heap two extra fields used by the runtime (Sync block index and Type handle). The type handle is a pointer to a Type object that describes the type of the instance, in this case type of Foo.

When you say new Foo() again, new space is allocated which will again contain space for the instance fields of the type. As you can see, instance fields are associated with object instances.

The runtime puts each instance field at a fixed offset from the start of the object's data. For example, myBar might live at offset +4. The address of the instance field is simply the address of the object plus the offset of the field.

Where do the static fields live?

Static fields in C# and Java are not associated with any object instance, but with a type. Classes, structs and enums are examples of types. Only once (per type) is some space allocated to hold the values of the static fields. It would make sense to allocate space for the static fields in the Type structure that describes the type, since there is also only one Type object per type. This is the approach taken by C# and Java.

The Type object1 is created when the type is loaded by the runtime. This structure contains all sorts of information needed for the runtime to be able to allocate new instances, call methods and perform casting, among other things. It also contains the space for the static fields, in this case bar and num.

The runtime has put each static field at some offset from the start of the type's data. This is different for each type. For example, bar might live at offset +64. The address of the static field is the address of the Type object plus the offset of the field. The type is statically known.

Displays some object structures, and their relationships.

1) In Microsoft .NET multiple different structures describe a type, such as the MethodTable and the EEClass structures.

Solution 2 - C#

This completely depends on the implementation in question. For C# and Java, the runtime is allowed to determine where to store the memory for the variable. For C and most compiled languages, the compiler makes this determination.

That being said, in practice, it doesn't matter. The usage it determined by specification, so you are free to use the variable knowing the behavior will be guaranteed.

Solution 3 - C#

For Java, objects referred to by static fields will reside on the heap like other objects:

> The heap is the runtime data area from which memory for all class instances and arrays is allocated.

The field will be initialised (if the declaration contains an initialization) when the class is loaded, which happens immediately before the first occurrence of any one of the following:

>- an instance of the class is created. >- a static method declared by the class is invoked. >- a static field declared by the class is assigned. >- a static field declared by the class is used and the field is not a constant variable (§4.12.4).

The access to the static field is done via 2 special JVM instructions, getstatic and putstatic. But apart from that distinction, static fields are similar to non static fields.

Solution 4 - C#

This varies wildly from language to language, and can even vary wildly from platform to platform...

For example, on the .NET side, static members are "associated" with the governing EEClass definition, which can be a heap-allocated OR a "wherever" allocated member (the C# spec doesn't specify heap/stack behavior, it's an implementation detail of the VM)

Solution 5 - C#

Im only familiar with C#, and this is my understanding of it:

Then your program starts, it loads all the related assemblies into an AppDomain. When the assambly is loaded, all static constructors are called, including static fields. They will live in the there, and the only way to unload them, is to unload the AppDomain.

Solution 6 - C#

There might be exceptions, but for reference types the new-keyword usually creates an object in an internal data structure called "heap". The heap is managed by the CLR (Common Language Runtime). It makes no difference whether you have a static or instance member or a local variable.

The difference between static members and instance members (the ones without the keyword static) is, that static members exist only once per type (class, struct) and instance members exist once per instance (per object).

It is only the reference which is static or not; this distinction does not apply to the referenced object (unless the object is a value type). A static member, an instance member and a local variable can all reference the same object.

Solution 7 - C#

Static members and constants are stored on heap. Unlike objects on heap that can get garbage collection, Static members and constants do stay till Appdomain is torn down, Hence once should be carefull in dealing with static fields

Solution 8 - C#

Static variables belong to the class not the object so there is only one bar in the memory even if you initialize thousands of instants of Foo.

Solution 9 - C#

This depends on the language to language or the designer of the language. If I talk about Java, static members store in the Method area of the JVM and all the object are linked to them. One more thing that is very important to know is that we can access the static data member without creating the object of the class.It means the allocation of the memory to the static data members doesn't depend on the creation of the object of that class.

Solution 10 - C#

By specification static variables are stored in Constant Pool. JVM stores this info in Permanent Generation.

Solution 11 - C#

Typically Static variables are stored on the data-segment of the program memory. so for every class that is created/is in the running program will create the static variable on data-segment and all other variables are initialized in the code segment.

so basically it is like

+++++++++++++++++++++++++++++++++++++
+ DATA Segment
+   -static vars
+   
+----------------------------------
+  instances | instances | instances|
+            |           |          |

here single area is shared among instances.

from wikipedia "The data area contains global and static variables used by the program that are
explicitly initialized with a value."

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKoray TugayView Question on Stackoverflow
Solution 1 - C#Daniel A.A. PelsmaekerView Answer on Stackoverflow
Solution 2 - C#Reed CopseyView Answer on Stackoverflow
Solution 3 - C#assyliasView Answer on Stackoverflow
Solution 4 - C#JerKimballView Answer on Stackoverflow
Solution 5 - C#Jens KlosterView Answer on Stackoverflow
Solution 6 - C#Olivier Jacot-DescombesView Answer on Stackoverflow
Solution 7 - C#Ashish GuptaView Answer on Stackoverflow
Solution 8 - C#Can GelişView Answer on Stackoverflow
Solution 9 - C#Jatin KhuranaView Answer on Stackoverflow
Solution 10 - C#MikhailView Answer on Stackoverflow
Solution 11 - C#JitendraView Answer on Stackoverflow