8

I am trying to clear all items from a ToolStripDropDownButton. Since they are disposable, I call the dispose method on each of them. But I see that after calling the dispose() method, the IsDisposed property still returns false. Why is that and how can I check if Dispose() is called on any object ? It is not a problem (I hope) in my current project, but I would really like to know what is going on here...

my code so far :

private void ClearDropDownAccessConnections()
{
    ToolStripItem button = null;

    for (int i = toolStripDropDownButtonAccess.DropDownItems.Count - 1; i > 0; i--)
    {
        button = toolStripDropDownButtonAccess.DropDownItems[i] as ToolStripItem;
        if ((button.Tag != null) && ((int)button.Tag == 10))
        {
            toolStripDropDownButtonAccess.DropDownItems.Remove(button);
            button.Dispose();
            //IF I CHECk HERE THEN button.IsDisposed IS STILL FALSE                }
        }
    }
Stefan Steinegger
  • 63,782
  • 15
  • 129
  • 193
GuidoG
  • 11,359
  • 6
  • 44
  • 79
  • ToolStripItems are "lean" controls, they don't use a window. And don't derive from the Control class. That often means that they don't actually have anything worth disposing. Makes them pretty buggy too. – Hans Passant May 07 '14 at 10:50
  • [More info on `IDisposable`](http://stackoverflow.com/a/538238/2478357). – Loetn May 07 '14 at 11:10

1 Answers1

4

For whatever their reason, the original .NET developers have decided to flip the IsDisposed flag only if the disposed ToolStripItem has non-null Owner property (which you're kindly indirectly setting to null line before). This doesn't seem to have any further impact - i.e. you can assume the ToolStripItem is safely disposed despite this weird behaviour.

As for your broader question - the IDisposable interface does not provide any way of checking if the object was disposed (and to make matters worse - classes implementing it do not have to guarantee an exception-free execution if it's called more than once (see MSDN)). You need to rely on the developers of said classes to provided some info if the object was actually disposed (which as can be seen in the ToolStripItem example is not a fool proof method), or track this somehow in your code.

Having said all that, it rarely becomes a problem in real-life scenarios (though it's useful to be aware of it).

decPL
  • 5,384
  • 1
  • 26
  • 36
  • Why don't the .NET developers give us a .Free method like in Delphi. – GuidoG May 07 '14 at 11:35
  • @user3611669 Mainly because one of the major ideas behind .NET is that you do not need a `Free` function, i.e. memory is managed by the runtime environment, not the developer (I don't want to get into a discussion on pros and cons). .NET's `Dispose` != Delhpi's `Free` (at least to the best of my limited understanding of Delphi), as in most normal scenarios `Dispose` will not affect the amount of free memory. – decPL May 07 '14 at 11:41