Search code examples
.netvb.netwinformsusing

Can still access a control's properties after it is disposed


I am using the following template below to show a modal form

Using tempForm As New CustomForm

    'Do Something

    StaticClass.StaticMemeber = tempForm
    tempForm.ShowDialog

End Using

'I can still access the properties of tempForm here
MsgBox(StaticClass.StaticMemeber.Text)

'However this below returns True
MsgBox(StaticClass.StaticMember.IsDisposed)


Public Class StaticClass

    Public Shared StaticMember as Control

End Class

Could someone help me understand why this is happening. Thanks.


Solution

  • An object that has been disposed still exists until the Garbage Collector deletes and frees the memory it is using. The IDispose interface is simply a pattern. One of the things that a object that implements that pattern should do is return an ObjectDisposed exeception for properties and methods after it has been disposed. However, nothing in the compiler or CLR forces an object to do that, its simply a pattern that the programmer that coded the object should implement. Until the garbage collector actualy deletes the obejct you can still access its properties. In this case the StaticMember still references the object. The GarabageCollector will not kill the object until that reference is released.