VB.NET has "Using"! Hurray!

While looking for something completely different, I found this in the MSDN documentation for Whidbey. VB.NET now has Using, which was one of the many constructs that C# had and that were missing in VB.NET.
Let me remind you what using is. If you're using a resource that needs to be disposed of, like a connection, a stream reader or some weird unmanaged COM object, you typically have to write something like that:
Dim A as SomethingThatImplementsIDisposable
Try
  A = new SomethingThatImplementsIDisposable
  ' Do something with A
Finally
  If not A is nothing Then
    A.Dispose()
  End If
End Try
Well, to do the same thing in C#, you would do this:
using (SomethingThatImplementsIDisposable A = new SomethingThatImplementsIDisposable()) {
  // Do something with A
}
And now, in VB.NET 2005, you can do this, which is pretty much the same thing as in C#, except for the curly brackets:
Using A as new SomethingThatImplementsIDisposable
  'Do something with A
End Using
This is very important because contracting the habit to use Using whenever possible not only makes your code simpler, it also makes it less error prone. And unreleased resources are one of the toughest bugs to spot because the problem does not appear during development but a lot later, usually when the application goes into production (if you're careless enough not to do any stress testing before release...) or even much later. The resources actually get released, but during garbage collection.
As a rule of thumbs, when you see yourself writing A.Dispose(), you should ask yourself if you can replace it with a Using block, whether you develop in C# or VB.NET.

1 Comment

  • C'est pas drole si les VBistes ont notre using maintenant aussi ;)

    Bon, bonne nouvelle, je connais un nouveau mot clé de Vb.net 2005 alors :D



    /GP

Comments have been disabled for this content.