In cases where Using
can't be used because IDisposable
is not implemented, is the following code an OK practice for With
/End With
? Would this cause a memory leak or would it be better to set an instance variable and then set it to nothing?
With New System.IO.FileInfo(sFileName)
' Do some work
End With
The With keyword has nothing to do with IDisposable or the Using keyword. It is just a handy short-cut to avoid having to type the name of the object reference.
Which is the same as:
Since FileInfo doesn't implement IDisposable, you otherwise do not have any use for Using. Do avoid assuming that With takes care of disposing the object reference used in the With statement. It doesn't. Does kinda make sense that it would but a good 15+ years of it being around stops the VB.NET team from altering its behavior so dramatically. It was never more than a short-cut to type less code. Featured pretty heavily in the "Why doesn't C# has the with keyword" questions of yore. Hot potato in the early days of C# but it hasn't been for a while now.