Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage collector and static class, variable

One point is wondering in my mind since last few days. I want to know how Garbage collector work with static classes, variables?

As we all know Garbage collector keep track of objects that has been created in application and removed them automatically when they are no longer in use. For static class no object is created and it loaded in the memory with the application debug.

So Garbage collector handle static classes?

like image 514
Amit Soni Avatar asked Nov 10 '11 13:11

Amit Soni


2 Answers

Static classes don't need to be removed since they are not objects and they don't consume memory (other than the actual class code being loaded by the .NET infrastructure). On the other hand static fields in static classes are objects that consume memory. They won't be collected since they are accessible for the full lifetime of the application. If you want to free the memory you should set the field to null so that the object the field has been pointing to becomes eligible for GC

like image 56
Stilgar Avatar answered Oct 05 '22 12:10

Stilgar


He is never gonna release them. ( e.g. in WEB its until restart of the IIS).

They'll never say :" No one is referencing me so i'm free to go"

also

you can never do new to Static Class.... so its usages is merely by Class object ( not the instance).

So .net doesn't take any chances and keep it out of GC.

like image 30
Royi Namir Avatar answered Oct 05 '22 12:10

Royi Namir