Can With/End With (VB.NET) be used when IDisposable is not available?

1k views Asked by At

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
3

There are 3 answers

2
Hans Passant On BEST ANSWER

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.

0
John Saunders On

With has nothing to do with memory or resource usage. It's just a shorthand notation.

1
Steve Massing On
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.