Warpin
Warpin

Reputation: 7043

WPF window class destruction

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?

Upvotes: 1

Views: 10041

Answers (3)

stiank81
stiank81

Reputation: 25696

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.

Upvotes: 3

Tony The Lion
Tony The Lion

Reputation: 63250

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.

Upvotes: 0

Charlie
Charlie

Reputation: 15247

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.

Upvotes: 1

Related Questions