Search code examples
c#dispose

what happens after I dispose an object?


I have a Label on my Form. when I call Dispose() method ,object removes from Form. But still I can set its properties. What happens after I call Dispose() Method for an object. can I recover it and show it again?

public void MyMethod()
{
     label1.Dispose();
     label1.Text = "Test";
     //No error happens
}

after disposing I can read some properties like Left property. It means label still exist in somewhere. How I can completely remove it?


Solution

  • What happens in this case, is that the control's handle is destroyed (and thus removed from its parent). After disposing, it can no longer be added to a visible display. However, the object itself, as in the class instance, still exists, and thus most properties can be set. (some will give an objectdisposed exception, such as trying to obtain the Handle property)

    In general, which properties can still be set, depends on an object's implementation (of the IDispose interface), and where it checks if it is disposed.