views:

329

answers:

3

I create a window like this:

if (someCondition)   
{  
   MyWindow wnd = new MyWindow();  
   wnd.Owner = this;  
   wnd.ShowDialog();  
}  

I want MyWindow's destructor to be called at the closing curly bracket, but it doesn't. Do I need to call something like delete/destroy for MyWindow's destructor to be called?

+1  A: 
using (MyWindow wnd = new MyWindow())
{
   wnd.Owner = this;
   wnd.ShowDialog();
}

This will call Dispose on your window after the curly brace, which is what I think you are looking for. Your MyWindow class will need to implement IDisposable.

Charlie
Not to be excessively pedantic, but the class already implements `IDisposable`; what it's going to need to do is override `Dispose`.
Robert Rossney
Robert: The WPF Window class doesn't implement IDisposable. (It doesn't hold any unmanaged resources.) Charlie's right, IDisposable needs to be implemented on the MyWindow derived class.
itowlson
Pedantry fail..
Charlie
A: 

One little thing, you're opening the window and then wanting call it's destructor. That doesn't really make sense. You should close the Window and then it's destructor will be called implicitly.

If you want to call it explicitly you should override Dispose in your MyWindow class. There you can clean up any resources that you want to explicitly dispose off.

Tony
`ShowDialog` doesn't return until the Windows is closed - so I don't understand your answer?
Benjamin Podszun
so if 'ShowDialog' doesn't return until the dialog is closed, how can one call the destructor if the dialog is still not destroyed? That's the point I'm trying to make.
Tony
+2  A: 

The "destructor" or finalizer as it is called in C# is called whenever the Garbage Collector feels like. You can trigger the Garbage Collector manually using System.GC.Collect(), but you probably don't want to do this. If your talking about Dispose() on the other hand you can make this being called by creating the window in a "using" clause:

using (var wnd = new MyWindow())
{
    wnd.Owner = this;  
    wnd.ShowDialog(); 
}

This would make wnd.Dispose() be called when the using clause is done, and would basically be the same as writing:

var wnd = new MyWindow(); 
wnd.Owner = this;  
wnd.ShowDialog();     
wnd.Dispose(); 

About the usage of the IDisposable interface this question might be helpful - and several more on StackOverflow.

stiank81