Last post Feb 09, 2013 06:36 PM by Paul Linton
Feb 09, 2013 08:20 AM|anand.sonawane|LINK
I have a Static class in which i have two methods. I wanted to know when does the memory get released for the methods?
Feb 09, 2013 09:16 AM|Rion Williams|LINK
Short answer: This class and methods will remain in memory for the lifetime of your application domain.
Since you are referring to a static class, then the methods within the static class are going to be considered static members as well (as static classes can only contain static members). The class itself is guaranteed to be loaded and have all of
the necessary fields inside instantiated before it is ever referenced with your code.
Once your class is loaded in this case, since it is a static class its constructor will only be called a single time, which will instantiate all of its properties and methods (referred to typically as fields) into memory and they will remain in
memory for the lifetime of your application domain (AppDomain).
This MSDN article on Static Classes covers this topic pretty well.
Feb 09, 2013 09:47 AM|anand.sonawane|LINK
Thanks alot Rion for your helpfull reply...but wanted to know that when does memory allocated to static class and its methods gets destroyed from AppDomain.
Feb 09, 2013 09:53 AM|Rion Williams|LINK
The CLR will allocate memory to your static fields during the loading of your application (as it isn't specified exactly when, but it is guaranteed to be loaded prior to ever being referenced).
When you end your application (and the AppDomain gets torn down), the memory allocated to your static fields will be released.
Feb 09, 2013 06:36 PM|Paul Linton|LINK
The memory used by your methods is part of the application. It is not allocated and deallocated (being a static or instance method or class makes no difference). The code of every method is continuosly allocated from when the application starts
until it is eventuallay exited (it may be paged in and out of physical memory but that is an entirely different kettle of fish).
On the other hand if you are asking about memory allocated for fields and/or properties then that is a different matter.
Methods are code, fields and properties are data. Very different things. Treated very differently as far as memory allocation is concerned.