Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to release all the resources of a class when I have done with it

How can I call a GC in .net when I have done with the object that i created for a class.

If I sets an object value as Null

objClassObject=NULL;

Does it releases all the objects and resources associated with it. ?

like image 485
Shantanu Gupta Avatar asked Dec 15 '25 18:12

Shantanu Gupta


2 Answers

Setting an object to null will not cause the GC to swoop in and clean up memory. It helps to first understand what you are doing, and luckily, the GC is well documented:

Links to Various GC related topics.

The answer is that 99.999% of the time (made up number, yes) you don't need to. If you have profiled and found that you actually do need to force a GC pass, you can use the GC class to attempt to do it. You really should know what you are doing though, and there is no guarantee that the GC will do exactly what you want.

Raymond Chen recently wrote a few good articles on this subject:

Everybody Thinks about the GC the Wrong Way

When Does an Object Become Eligible for Garbage Collection?

However, if you create a class that manages some native resource, you will then want to implement the IDisposable interface as the GC will not / cannot reclaim unmanaged resources.

like image 187
Ed S. Avatar answered Dec 17 '25 09:12

Ed S.


The short answer is: GC.Collect(). However, the correct answer is that you should not concern yourself with the details of the GC. Let .NET manage your objects for you. If objClassObject goes out of scope, it's eligible for garbage collection and the GC will make sure it gets collected for you.

like image 21
Steve Michelotti Avatar answered Dec 17 '25 09:12

Steve Michelotti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!