Can With/End With (VB.NET) be used when IDisposable is not available?
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.
With New System.IO.FileInfo(sfilename)
Console.WriteLine(.Length) '' note the dot without an object reference
'' etc..
End With
Which is the same as:
Dim info = New System.IO.FileInfo(sfilename)
Console.WriteLine(info.Length)
'' etc..
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.
With
has nothing to do with memory or resource usage. It's just a shorthand notation.
With
is more than just shorthand notation. If you setting a large number of properties on an object with can slightly improve performance per MSDN, "If the qualification path to the object is long, using With...End With can improve your performance." (See Remarks on http://msdn.microsoft.com/en-us/library/wc500chb.aspx ) The reason it does this this is that a with block will only have to get the object reference one time and then it reuses that object reference for each subsequent call. If you explicitly list the object each time the runtime has to get the object reference multiple times. It's not a big difference but it can be important in some cases.
精彩评论