Using..End Using Statement
As an alternative to directly invoking Dispose
, you can take advantage of the Using..End Using
statement. This code block automatically releases and removes from memory the object that it points to, invoking Dispose
behind the scenes for you. The following code shows how you can open a stream for writing a file and ensure that the stream will be released even if you do not explicitly close it:
Using dp As New IO.StreamWriter("C:\TestFile.txt", False) dp.WriteLine("This is a demo text")End Using
Notice how you simply create an instance of the object via the Using
keyword. The End Using
statement causes Dispose
to be invoked on the previously mentioned instance. The advantage of Using..End ...
Get Visual Basic 2015 Unleashed now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.