Wednesday, October 31, 2012

The using function in VB.NET

The using function in VB.NET


In VBA or some other programming language, you offend need to make sure you declare, create and clear an object.
Check this VBA sample (totally fake I know):

Public Sub vbatest()

    Dim oDocument As Document
    Set oDocument = New Document

    'do something here

    Set oDocument = Nothing

End Sub


But what if you want to do thing like the old fashion way. What if you want to tell exactly with to set an object to nothing?
Using Visual Studio 2010, I’ll show you 2 code samples. The first one is the simple way. The second one uses the using function.

''' <summary>
''' put a Timer without the Visual Basic form Designer
''' </summary>
''' <remarks></remarks>
Public Class Form1
    Private WithEvents oTimer As System.Windows.Forms.Timer

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        oTimer = New System.Windows.Forms.Timer
        oTimer.Interval = 1000
        oTimer.Enabled = True
        oTimer.Start()
        If oTimer Is Nothing Then
            MsgBox("oTimer is Nothing")
        End If
    End Sub

    Private Sub timerTicks() Handles oTimer.Tick
        Me.Text = Date.Now
    End Sub

End Class







 This is the second sample with the Using function


''' <summary>
''' put a Timer without the Visual Basic form Designer
''' </summary>
''' <remarks></remarks>
Public Class Form1
    Private WithEvents oTimer As System.Windows.Forms.Timer

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Using oTimer = New System.Windows.Forms.Timer
            oTimer.Interval = 1000
            oTimer.Enabled = True
            oTimer.Start()
        End Using
        If oTimer Is Nothing Then
            MsgBox("oTimer is Nothing")
        End If
    End Sub

    Private Sub timerTicks() Handles oTimer.Tick
        Me.Text = Date.Now
    End Sub

End Class




The using function makes sure your object you use is set to nothing after it leaves the End Using.
I don’t have any practical situation where you could use or not the Using function.
Please note that an Object is not necessary deleted when the function ends. In fact, never assume your object is set to nothing automatically.

The program I love to use:


Sample Code : TimerSample.zip

1 comment:

  1. Thanks for this informative post. This post is very helpful for my project.conception de site web

    ReplyDelete