Parameters

rbulph

Junior Contributor
Joined
Feb 17, 2003
Messages
397
How can I pass:

a) the AddressOf a procedure so as to use it with AddHandler; and
b) a Type so as to use it with TypeOf;

as parameters to a procedure?
 
(A)
Visual Basic:
Class Example
    'Declare Event
    Event SampleEvent As EventHandler
    
    Sub PassHandler()
        'Create Delegate
        Dim NewHandler As EventHandler = AddressOf Handler
        'Pass Delegate
        AttatchHandler(NewHandler)
    End Sub
    
    Sub AttatchHandler(Handler As EventHandler)
        'Attatch Delegate
        AddHandler SampleEvent, Handler
    End Sub
    
    'Use Delegate
    Sub Handler(Sender As Object, E As EventArgs)
        MessageBox.Show("Handled")
    End Sub
End Class
(B)
Visual Basic:
Class Example
    Sub PassType
        'GetType returns the runtime type of an object.
        Dim T As System.Type = Me.GetType()
        'The System.Type can be passed as a parameter.
        MessageBox.Show(IsMyType(T).ToString)
    End Sub
    
    Function IsMyType(System.Type T) As Boolean
        Dim MyType As System.Type = Me.GetType()
 
        If (MyType Is T) Or (T.IsSubclassOf(MyType)) Then
            'The above expression is the same as
            'If TypeOf(AnotherObject) Is TypeOf(Me).
            'We check if the two types are exactly the same (MyType Is T)
            'or if T is derived from MyType.
            Return True
        End If
        Return False
    End Function
End Class
I did not test the code, so I am not sure it is 100% correct, but you can certainly get the jist of it.
 
Back
Top