Are there any downsides to using Using? I understand that outside of a Using block I’m not going to be able to use that resource but are there circumstances where I should leave it to the garbage collector?
Here is some example code with nested usings.
Dim ftpReq As FtpWebRequest = Nothing
subSetupFtp(ftpReq, WebRequestMethods.Ftp.ListDirectory) 'Setup FTP
Dim lstFileNames As New List(Of String)
'Get FTP response
Using webRes As WebResponse = ftpReq.GetResponse()
'read filenames into list to return
Using ftpStream As New StreamReader(webRes.GetResponseStream())
Do While ftpStream.Peek <> -1
lstFileNames.Add(ftpStream.ReadLine)
Loop
lstFileNames.Sort() 'alphabetically sorts the list(a-z) ie. The files are now in date order
'Tidy up
ftpStream.Close()
webRes.Close()
End Using
End Using
If an object has IDisposable implemented with then, it is always better to use it with
Using, which internally works as a try / finally block. This will ensure its disposal even if any exception occurs.IDisposable.