If I understand correctly the .net runtime will always clean up after me. So if I create new objects and I stop referencing them in my code, the runtime will clean up those objects and free the memory they occupied.
Since this is the case why then do some objects need to have a destructor or dispose method? Won’t the runtime clean up after them when they are not referenced anymore?
Finalizers are needed to guarantee the release of scarce resources back into the system like file handles, sockets, kernel objects, etc. Since the finalizer always runs at the end of the objects life, it’s the designated place to release those handles.
The
Disposepattern is used to provide deterministic destruction of resources. Since the .net runtime garbage collector is non-deterministic (which means you can never be sure when the runtime will collect old objects and call their finalizer), a method was needed to ensure the deterministic release of system resources. Therefore, when you implement theDisposepattern properly you provide deterministic release of the resources and in cases where the consumer is careless and does not dispose the object, the finalizer will clean up the object.A simple example of why
Disposeis needed might be a quick and dirty log method:In the above example, the file will remain locked until the garbage collector calls the finalizer on the
StreamWriterobject. This presents a problem since, in the meantime, the method might be called again to write a log, but this time it will fail because the file is still locked.The correct way is to dispose the object when are done using it:
BTW, technically finalizers and destructors mean the same thing; I do prefer to call c# destructors ‘finalizers’ since otherwise they tend to confuse people with C++ destructors, which unlike C#, are deterministic.