Post

VB 2005 Gems #1

While working with VB 2005, I’ll try to take note of the little things that help make VB stand out above other development products. Here’s one that I haven’t really heard anyone speak upon and it kind of surprised me when I used it the first time. Don’t get me wrong, it was a wonderful surprise; one of those “why didn’t it (the IDE) do that before” sort of thing.

When you have a class that is clinging onto some resource during its lifetime, it is appropriate to implement IDisposable so that whatever resource is being “locked” can be released in a couple of different ways.

So with just 17 keypresses, (Implements IDis tab tab enter) you end up with the following in your code window.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Public Class SomeIDisposableClass
  Implements IDisposable

  Private disposedValue As Boolean = False   ' To detect redundant calls

  ' IDisposable
  Protected Overridable Sub Dispose(ByVal disposing As Boolean)
    If Not Me.disposedValue Then
      If disposing Then
        ' TODO: free unmanaged resources when explicitly called
      End If

      ' TODO: free shared unmanaged resources
    End If
    Me.disposedValue = True
  End Sub
 
#Region " IDisposable Support "
  ' This code added by Visual Basic to correctly implement the disposable pattern.
  Public Sub Dispose() Implements IDisposable.Dispose
    ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
    Dispose(True)
    GC.SuppressFinalize(Me)
  End Sub
#End Region

End Class

So not only does this code automagically get added for you, saving you from having to remember everything your supposed to do to implement “The IDisposable Pattern” or having to press F1 on the IDisposable keyword then copy and paste it into the code window… just to get to this point, you can get what you need to get done.

(Note that C# doesn’t do this… smiles)

This post is licensed under CC BY 4.0 by the author.