Need to Dispose() of menu item?

C

Chien Lau

Hi,

Consider the following code where 'CM' is a reference to a ContextMenu:

MenuItem[] menuItems=new MenuItem[]{
new MenuItem("Add",new EventHandler(MI_Click)),
new MenuItem("Remove",new EventHandler(MI_Click))
};
CM=new ContextMenu(menuItems);

In the Dispose() override for my containing form, clearly I'll want to
call Dispose against 'CM'. Must I call Dispose() against the inner MenuItems
that were assigned to 'CM' as well? Does calling CM.Dispose() automatically
Dispose() of the MenuItems that 'CM' contains? I imagine not since the user
may want to reuse these MenuItems for other purposes after the disposal of
CM.

Thanks...
 
J

Jon Skeet [C# MVP]

Chien Lau said:
Hi,

Consider the following code where 'CM' is a reference to a ContextMenu:

MenuItem[] menuItems=new MenuItem[]{
new MenuItem("Add",new EventHandler(MI_Click)),
new MenuItem("Remove",new EventHandler(MI_Click))
};
CM=new ContextMenu(menuItems);

In the Dispose() override for my containing form, clearly I'll want to
call Dispose against 'CM'. Must I call Dispose() against the inner MenuItems
that were assigned to 'CM' as well? Does calling CM.Dispose() automatically
Dispose() of the MenuItems that 'CM' contains?

I believe it does.
I imagine not since the user may want to reuse these MenuItems for
other purposes after the disposal of CM.

I think that's going to be a far rarer situation than yours.

You could always check by deriving your own class from MenuItem,
overriding Dispose, adding one to a ContextMenu, and then seeing what
happens if you dispose of the ContextMenu.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top