If I initialize a class with the Using
statement, is it necessary to call it's Close method upon early termination?
Using xmlstream As New MemoryStream()
Try
'Do runtime operation
Catch ex As Exception
Console.WriteLine("Could not fill dataset. REASON: " & ex.Message)
xmlstream.Close() '<- NECESSARY????
Environment.Exit(-1) '<- Early termination!
End Try
'DO STUFF
End Using
Not it is not necessary. According to the IDisposable.Dispose Method documentation
"The using statement automatically closes the stream and calls Dispose on the object when the code that is using it has completed"
Having said that it is not a good idea to have Environment.Exit
within a Using block as this does not call Close
, or indeed Dispose
. Instead you should refactor this as a function that returns True or False and act on that return value to decide whether to Exit or not