C#: "using" when instantiating a form?
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;
us开发者_运维百科ing (f = new MyForm())
{
f.ShowDialog();
}
Additional question:
Could the following code be substituted?
using (MyForm f = new MyForm())
{
f.ShowDialog();
}
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.
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
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
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())
精彩评论