Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: "using" when instantiating a form?

Tags:

c#

winforms

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();
}
like image 554
Craig Johnston Avatar asked Oct 15 '10 03:10

Craig Johnston


3 Answers

A Form in WinForms implements the IDisposable pattern (it inherits IDisposable from Component. The original author is correctly ensuring that the value will be disposed by means of the using statement.

like image 84
JaredPar Avatar answered Oct 09 '22 03:10

JaredPar


Perhaps. If MyForm implements IDisposable, this will ensure that the Dispose method is called if an exception is thrown in the call to ShowDialog.

Otherwise, the using is not necessary unless you want to force disposal immediately

like image 3
RyanHennig Avatar answered Oct 09 '22 01:10

RyanHennig


This restricts the resources held by the MyForm object f to the using block. Its Dispose method will be called when the block is exited and it is guaranteed to be "disposed" of at that time. Therefore any resources it holds will get deterministically cleaned up. Also, f cannot be modified to refer to another object within the using block. For more details, see the info about using in MSDN:


using in the C# Reference

like image 3
Michael Goldshteyn Avatar answered Oct 09 '22 02:10

Michael Goldshteyn