From my understanding an interfaced resource is freed once the reference count on the interface gets to 0.
Consider the following private field:
private IMyInterface _field = new DisposableObject()
Would I need to still explicitly free this field up in the class e.g. make the class implemented IDisposable and free it up on Dispose? Or would it be freed up automatically because I am using an interface?
I had a similar situation in Delphi and it was causing a memory leak which confused me a little as I always thought interfaced objects did not need to be freed (as they are reference counted). To fix the memory leak, I had to store the concrete type and free it up on destroy.
I guess what I am really getting at is why do I need to free it up if I am using an interface?
.NET does not use reference counting to determine when resources are garbage collected. Objects will be collected when there are no live references to an object anywhere in the program. This is done by an object-graph traversal rather than reference counting, so that circular references do not leak resources.
If a class with unmanaged resources is coded correctly, then the call to
Disposewill be optional. The resources will be cleaned up in the finalizer when the garbage collection occurs regardless.Disposedoes not affect the lifetime of an object. It will be garbage collected at some time after there are no live references to the object remaining.The lifetime of an object is also not affected by whether the variable that references it is of an interface or object type. Setting the variable to null will remove the live reference and—if there are no other references to the object—allow the object to be collected.