10

I understand the concept and reasons behind using the using statement, and I use it with things like file resources and remote connections, I was wondering if it is good practice to use the using statement with WinForm forms and dialogs?

using (MyDialog dlg = new MyDialog())
{
    if (dlg.ShowDialog() == EDialogResult.OK)
    {
        // Do Something
    }
}

Thanks!

1
  • Good point. What's the overheard of wrapping everything in try/catch/finally blocks? Commented Feb 4, 2011 at 12:04

1 Answer 1

8

With Dialogs only. But then it is a very good practice.

You will find that it doesn't work around Show(), because using(){} can only be used inside 1 method and you never want to Close again right after a Show().

Sign up to request clarification or add additional context in comments.

7 Comments

Of course that makes sense in regards to only using with dialogs. :)
I dont understand why you'd need a Dispose with ShowDialog while with Show you dont.. creates some inconsistency in my code every time. i usually also add a using around ShowDialog, but only to make my profiler not list it as disposable instance that hasn't been disposed. is there a real reason why it should be disposed?
@stmax it depends on the scope of the form being shown. ShowDialog will 'block' until the form is closed so the using block wont terminate until after the form has closed. Show on the other hand returns 'instantly' so you would end up disposing an object that is still in use.
What abount Pens, Fonts, Brushes? Why only dialogs? Do you make your suggestion based on the overhead of the try/catch/finally that is generated?
@Steve: Of course you use using for Pens etc too. This was about the 2 types of Forms only.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.