Vanderson Assis
Vanderson Assis

Reputation: 158

How does c# handle the memory for static members

Made a lot of searches but none ended up clarifying my doubt.

When one use a static class or method, when does c# allocates memory for them? And does it get deallocated at all?

Bonus question: When should one use a static member or class?

Upvotes: 0

Views: 1043

Answers (2)

Ondrej Tucny
Ondrej Tucny

Reputation: 27964

When one use a static class or method, when does c# allocates memory for them?

It's not C# who allocates memory, it's the underlying CLR. You also should differentiate allocation of memory and actual initialization of members.

The allocation of memory can happen when the program (EXE, DLL) is loaded into the memory. This is because in a “typical” implementation static data memebers are allocated on the so called data segment. That's a fixed portion of memory dedicated to hold permanent (from the run-time perspective) data structures. However, a specific implementation may work a bit differently, even though will have to be some sort of a static data segment, at least holding pointers to other data structures.

The initialization happens before the class is first accessed.

And does it get deallocated at all?

No. They are static.


Bonus question: When should one use a static member or class?

Side note: This is not a bonus question, but rather a reason for closing a question as primarily opinion based.

Upvotes: 4

Konstantin Ershov
Konstantin Ershov

Reputation: 740

https://msdn.microsoft.com/en-us/library/79b3xss3.aspx

As is the case with all class types, the type information for a static class is loaded by the .NET Framework common language runtime (CLR) when the program that references the class is loaded. The program cannot specify exactly when the class is loaded. However, it is guaranteed to be loaded and to have its fields initialized and its static constructor called before the class is referenced for the first time in your program. A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides.

Upvotes: 4

Related Questions