Why do you need to initialize the dialogue using the statute?

I am adapting the coding style guide from this source: http://www.csharpfriends.com/articles/getarticle.aspx?articleid=336

In the "5.2 Initialization" section, he recommends the following:

If you are initializing a dialog, try using the using statement:

using (OpenFileDialog openFileDialog = new OpenFileDialog ()) {}

What are the reasons for choosing this style?

+6
c # coding-style idisposable
source share
7 answers

Most likely you only need a short dialog for immediate input. Thus, using the using statement, you can free resources after you finish what you need (Dispose it).

Usage is just syntactic sugar for calling the dispose method after use.

+4
source share

OpenFileDialog implements the IDisposable interface. Given that dialogs usually have the lifetime of a particular method, the using block ensures that they are correctly located

 using (OpenFileDialog dialog = new OpenFileDialog()) { // Some setup work ... return dialog.ShowDialog(); } 
+3
source share

This is not a good example; OpenFileDialog already has all the resources when the dialog closes. And this is a component, not a control. However, this implementation detail. In general, calling ShowDialog () does not automatically delete the form object. Unlike Show (). This is necessary to get the results of the dialog without fear of an ObjectDisposedException. Now it’s important that you dispose of it yourself after that.

Which facilitates the use of instructions.

+3
source share

You would do this for the same reason that you would use it using a construct that should ensure that the object is deleted. OpenFileDialog implements IDisposable, so the user must ensure that the instance is deleted, and the use constructor ensures that .Dispose is called on the object.

+1
source share

The using statement in C # allows you to define the area for the lifetime of an object. This statement receives the specified resource, executes the statements, and finally calls the Dispose () method of the object to clear.

0
source share

Using definition

using : Defines the area beyond which the object or objects will be deleted.

I think the definition says it all.

For a better understanding read using Statement in msdn

what-is-the-c-using-block-and-why-should-i-use-it

Get more information

0
source share

One of the key points not mentioned in the other answers is that all dialogs are always modal, which means that unlike ordinary forms that you can show, modal dialogs block execution until the form disappears. This means that by the time execution is returned to you after the dialog is shown, the dialog has already disappeared! Thus, it is time to dispose of it, so it is recommended to use the usings operator.

0
source share

All Articles