Static Variable in C#

Each time when we create a new instance of a class we get a new copy of the instance data to play with.

The instance methods of the class work on the instance data.  The instance data is completely independent of the instance data in all other classes.  If we change a value in one instance it has no impact on the same value in other instances.

Static data is equivalent to global data.

Everybody in the program sees the same data. If someone changes the data then everybody else will see the change as well.

When you create an instance of a class you are effectively allocating some memory to hold your own copy of the instance data defined by the class.  If you create 5 instances of a class then you get 5 separate memory locations where each location has its own copy of the instance data.  Each memory block is independent of the others.

There is only one copy of static data in memory in general. Static variables are stored on the Managed Heap, not the Stack, when the type is first referenced.  The Type Object of the compiled class contains a reference to the object. (This heap is separate from the normal garbage collected heap – it’s known as a “high frequency heap”, and there’s one per application domain.)

The Type Object of a class will stay in memory until the AppDomain where it resides is unloaded.  Since the object on the Heap is always being referenced by the compiled Type Object, static objects on the Heap will never by GC’ed and will always consume memory until the AppDomain is unloaded.

Vikas Jindal


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s