Alex Rivera | Logout

C#: "using" when instantiating a form?

Asked 2010-10-15T03:11:07.910
11

I am looking at some C# code written by someone else. Whenever a form is instantiated and then shown, the following is done. Is this correct? Why would you use "using" in this context?

MyForm f;
using (f = new MyForm())
{
    f.ShowDialog();
}

Additional question:

Could the following code be substituted?

using (MyForm f = new MyForm())
{
    f.ShowDialog();
}
Edit
Report

1 Answer

0

Yes, this is a 'correct' usage of IDisposable. Perhaps the author of MyForm had some large object (say a large MemoryStream) or file resource (e.g. an open FileStream) that it opened and wanted to make sure was released ASAP. Calling the MyForm ctor inside a using statement would be helpful in this case.

Question 2:

in C# 3.0+, you can use the shorter (and just as clear):

using (var f = new MyForm())

answered 2010-10-15T04:08:56.330

Your Answer