Dispose
refers to a mechanism to explicitly clean up the un-managed memory
, since that cannot be cleaned up using standard Garbage Collector
, mostly IDisposable
will be implemented by the class, which use the unmanaged API internally like Database Connection
.
Standard practice is:
To also implement Finalizer
along with, since Dispose
is an explicit call and if missed out by caller then Finalization does take care of clean up action, though it needs 2 cycles of GC.
If a class use any of the object, as a class variable, which implements a Dispose
itself, then the Dispose shall be implemented to call the Dispose
on the class variable.
Regarding the code provided:
if(RecordCollections!=null){
RecordCollections.Clear();
RecordCollections=null;
}
Or
RecordCollections = null;
As this is related to cleaning up managed memory, it has little use, since GC
does the main job and doesn't need it, but in my view its an acceptable practice
, where class variables are explicitly nullified, which makes user vary of each and every allocation and mostly an attempt shall be made to use the method local variables, until and unless state needs to be shared across method calls. Object allocation misuse, can be much more controlled.
As far as difference is concerned, though a collection is explicitly cleared and then nullified or just nullified, the memory remains intact, till the point GC
is invoked, which is un-deterministic
, but in my view its not very clear, how does the GC
explicitly maps the objects for collection, which are no more reachable, but for various generations, especially the higher ones (promoted objects), if an object is explicit marked as null
, then GC may have to spend less / no time tracing the root / reference, however there's no explicit documentation, to explain this aspect / implementation.