Search code examples
c#memory-leaksdisposeusing

Dispose a object been added to a collection, but the collection still has reference to it


Read some code from a legecy system.

Say I have a instance of class A, then added it to a collection, then dispose it.

I just can not understand what's the point to use implicit dispose here since the code still use the myControlCollcetion,which means the cltCheckBoxA wont be really freed anyway.

Why?

using (UserControlA cltCheckBoxA = new UserControlA())
{
    //some operation
    base.myControlCollcetion.Add(cltCheckBoxA);
}

//Other operation against myControlCollcetion

Solution

  • Disposing an object is entirely different from freeing it's managed memory (which is what the GC does). Dispose is explicitly cleaning up all unmanaged resources that the garbage collector can't free.

    This means that when the object is used after Dispose is called on it there are a lot of possibilities. (This is not an exhaustive list.)

    1. Many objects are essentially unusable once their unmanaged resources are cleaned up. In this case, it's common for them to throw an exception whenever one of their members is accessed.
    2. The object could just act in an unexpected manor because it is being used after it is disposed. It might result in weird exceptions, or just incorrect results from methods, or, really, anything.
    3. It may never have actually had unmanaged resources. Some objects implement IDisposable just so that they are more extensible, or to try to future-proof them. DataTable is an example of this; it's Dispose does nothing. In this case, the object will work just fine after it is disposed.
    4. It's possible that the object is still usable even without its unmanaged resources. Maybe only a portion of it's functionality becomes unusable after Dispose is called, in which case as long as only those limited aspects are used later on it will work just fine.
    5. Some object might re-create it's unmanaged resources when accessed after it is disposed. It would be bad practice, but it's your class you can do what you want.