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. ?
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. ?
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.
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.
It's a managed world. you don't need to worry about it until your class has unmanaged resurces in this case use Disposal pattern.
GC itself deals with only managed resources
. So if you have no unmanaged code/resources in this case they will not be released until there is no Finalizer there with code to release unmanaged resources.
Also note that there is no need to set object to null
so GC will clean that. GC can detect itself that there are no references and the object is not needed and it will be cleaned on next GC cycle...
As for calling GC, you can use GC.Collect()
, but is highly recommended not to do that(unless for some extreme cases) as it is optimized when to be called.