Search code examples
.netvb.netexceptiondisposeidisposable

How to launch programatically a "Object reference not set to an instance of an object" exception?


I have written a class with Idisposable like this

Public Class WndProcClass
    Inherits NativeWindow
    Implements IDisposable

#Region " IDisposable "

Private disposedValue As Boolean ' To detect redundant calls

Public Sub Dispose() Implements IDisposable.Dispose
    Dispose(True)
    GC.SuppressFinalize(Me)
End Sub

' IDisposable
Protected Overridable Sub Dispose(disposing As Boolean)

    If Not Me.disposedValue Then

        If disposing Then
            Me.form = Nothing
            Me.ReleaseHandle()
            Me.DestroyHandle()
        End If

    End If

    Me.disposedValue = True

End Sub

#End Region

end class

In the form1 I declare this:

Public WithEvents WindowsMessages As New WndProcClass(Me)

And here I try to dispose the object and to call one method

private shadows sub Shown() handles mybase.shown
    WindowsMessages.Dispose()
    WindowsMessages.myMethod(myParams)
end sub

Well, the thing is that after disposing the object I will prevent some kind of errors by throwing an Object reference not set to an instance of an object when I try to call a method from the object after calling Dispose method, literally I want to turn the object to nothing after disposing it, automatically, like the native framework idisposable objects does.

so, I want to make the same prevention like when is done by setting the object as nothing

private shadows sub Shown() handles mybase.shown
    WindowsMessages = Nothing
    WindowsMessages.myMethod(myParams) ' object reference exception is throwed here
end sub

How I can do it?


Solution

  • In the method you would check if the object is disposed, and throw an appropriate exception.

    For example:

    If Me.disposedValue Then
      Throw New ObjectDisposedException("WndProcClass")
    End If