Imports System.IO

Public Class MyFile
    Implements IDisposable
    ' members...
    Private _stream As FileStream
    Private _isDisposed As Boolean


    ' Constructor...
    Public Sub New(ByVal filename As String)

        ' create, or append to the file...
        _stream = New FileStream("c:\FinalizeDemo.txt", _
                      FileMode.OpenOrCreate)

        ' tell the user...
        Console.WriteLine("Object " & GetHashCode() & " created.")
        Console.WriteLine("Using file: " & filename)

    End Sub


    ' AddText - add some text to the file...
    Public Function AddText(ByVal buf As String)

        ' have we been disposed?
        If _isDisposed = True Then
            Throw New ObjectDisposedException("I've been disposed!")
        End If

        ' write the time and the message...
        Dim writer As New StreamWriter(_stream)
        writer.WriteLine(Date.Now)
        writer.WriteLine(buf)
        writer.Close()

    End Function


    ' Dispose - called when we need disposing...
    Public Sub Dispose() Implements System.IDisposable.Dispose

        ' have we already been disposed?
        If _isDisposed = True Then Return

        ' clean up our resources...
        _stream.Close()
        _stream = Nothing

        ' flag us as being disposed...
        _isDisposed = True

        ' tell the GC not to collect us...
        GC.SuppressFinalize(Me)

        ' tell the user that we've been disposed...
        Console.WriteLine("Object " & GetHashCode() & " disposed.")

    End Sub


    ' Finalize - called when we're finalized...
    Protected Overrides Sub Finalize()

        ' call dispose...
        Dispose()

        ' tell the user that we've been finalized...
        Console.WriteLine("Object " & GetHashCode() & " finalized.")

    End Sub



End Class
