Click here to Skip to main content
15,889,595 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

If i have a class with some statics filed like below:

C#
class Test{

public static SomeotherClass _someotherclassObj=new SomeotherClass();

//other members and method..

}


If i have 100 instances of class Test, will those instances will be marked reachable by Garbage Collector (because of static member) and will remain till application ends.

Thanks!!
Rahul
Posted
Updated 2-Apr-12 17:45pm
v2

Static objects are always marked to be NOT garbage collected until they are set to NULL.
Here is a nice article that explains a bit more about the topic:
http://msdn.microsoft.com/en-us/magazine/bb985010.aspx[^]
 
Share this answer
 
Objects referenced by static variables will only be garbage collected when the relevant AppDomain is garbage collected. In client applications, there's often just a single AppDomain which lives for the duration of the process. (An exception is when the application uses a plug-in architecture - different plug-ins may be loaded in different AppDomains and the AppDomain may be unloaded later.)

In ASP.NET, "AppDomain recycling" happens periodically (for various reasons) - when this occurs, and the static variables within that AppDomain will no longer act as GC roots, and thus won't prevent objects being garbage collected.

If you were worried about an object being garbage collected while you still had a reference to it via a static variable, though, you can relax. While you can access the object, it won't be garbage collected.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900