Search code examples
vb.neterror-handlingusing-statement

VB.NET: question about "using" block


Consider the code:

On Error Goto ErrorHandler

Using sr As StreamReader = New StreamReader(OpenFile)
    str = sr.ReadToEnd
    sr.Close()
End Using

Exit Sub

ErrorHandler:

If there is an error inside the Using block how do you clean up the sr object?

The sr object is not in scope in ErrHandler so sr.Close() cannot be called. Does the Using block cleanup any resources automatically even if there is an error?


Solution

  • Yes, the using block will automatically call IDisposable.Dispose (which, for a StreamReader is the same as calling Close) so there's nothing you need to do (that's the whole point of using blocks!)