O'Reilly logo

Microsoft® Visual Basic® 2010 Developer’s Handbook by Klaus Löffelmann and Sarika Calla Purohit

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Targeted Object Release with Using

Objects that accept information about their disposal implement a method called Dispose, as you have already learned. When you call Dispose on an object, it simultaneously frees all reserved system resources and signals the GC that it’s free to be destroyed. You’ve seen how to implement such a pattern in your own classes, but what’s the best way to call Dispose?

The following simple code writes some text into a file, but demonstrates typical usage:

Dim locSw As StreamWriter
Try
    locSw = New StreamWriter("C:\Textfile1.txt")
    Try
        locSw.WriteLine("First line of text")
        locSw.WriteLine("Second line of text")
        'Empty write buffer
        locSw.Flush()
    Catch ex As Exception
        Debug.Print("Error while writing the file!")
    Finally
        'Free ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required