When to use the Using statement

I think I may use the Using statement here incorrectly. What would be the best way to write this?

Dim x As New Serialization.XmlSerializer( ... ) Using file As New FileStream(myFile, FileMode.Create) Using writer As XmlWriter = XmlTextWriter.Create(file) x.Serialize(writer, myCollection) End Using End Using 

I read that you should only use the using block for objects with .Dispose() (i.e., implements IDisposable), so I think there should not be a "Use on," writer, but instead writer.Close() at the end, but the β€œfile” has both .Dispose() and .Close() , so I use? using or file.Close() ?

Note. I use XmlWriter because I can customize the output. However, I deleted the settings.

+4
source share
5 answers

Both FileStream and XmlWriter implement IDisposable - the code is correct. In fact, the compiler would probably not allow you to do this if it weren't right. If there is no public .Dispose() , then it should use an explicit implementation of the interface, but this does not change your responsibility for calling .Dispose() . For interest in C #, you can avoid the ever-increasing attachment / indentation i.e.

 using(...a...) using(...b...) using(...c...) { ... } 

but fundamentally your current code is correct.

+11
source

This is really confusing and has been the subject of much debate. This is the implementation of the Dispose () method:

 Public Sub Dispose() Me.Close End Sub 

In other words, calling Dispose () does the same thing as calling Close (). You definitely want to use the Using statement here.

+3
source

Yes, the .Close and .Dispose bit unsuccessful.

This (was?) The official MS manual. The Close method is called the Domain Destination .

And, like the word Alias, you can assume that they are doing exactly the same thing. Normally, Close simply calls Dispose.

The Using ... End Using block will only compile with a link that is IDisposable (has .Dispose)


General advice:

  • If the class has .Dispose, use the Using block.
  • Using simply short for Try ... Finally , and you can refuse it. But
  • Do not try to combine or save multiple blocks.
  • When nesting goes to depth (> 3..5), specify an additional method.
+2
source

Your code looks correct. Note that you will get a compile-time error if you try to use using for a data type that does not support IDispose .

+1
source

I would like to do both, but it could be because I'm a little old fashioned. If I opened the file (which you have), I will obviously close it. Regardless of whether the Dispose method performs a clean close before the implementation of the object, and not to the client. But since the object still implements IDisposable, you still need to call it.

+1
source

Source: https://habr.com/ru/post/1344509/


All Articles