Delegates + Remove method
Code:
Public Delegate Sub BeginingDelegate()
Public Sub SingleCall1()
MsgBox("Delegate 1")
End Sub
Public Sub SingleCall2()
MsgBox("Delegate 2")
End Sub
Public Sub SingleCall3()
MsgBox("Delegate 3")
End Sub
'USE COMBINE METHOD
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Call1 As BeginingDelegate
Dim Call2 As BeginingDelegate
Dim Call3 As BeginingDelegate
Call1 = AddressOf SingleCall1
Call2 = New BeginingDelegate(AddressOf SingleCall2)
Call3 = New BeginingDelegate(AddressOf SingleCall3)
Dim multiExecution As BeginingDelegate = CType([Delegate].Combine(Call1, Call2, Call3), BeginingDelegate)
multiExecution.Invoke()
End Sub
'USE REMOVE METHOD
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim Call1 As BeginingDelegate
Dim Call2 As BeginingDelegate
Call1 = AddressOf SingleCall1
Call2 = New BeginingDelegate(AddressOf SingleCall2)
Dim multiExecution As BeginingDelegate = CType([Delegate].Remove(multiExecution, Call2), BeginingDelegate)
multiExecution.Invoke()
End Sub
Combine method is working successfully,But Remove method not working Successfully .Now I want to remove delegate SingleCall2 on Button2_Click,I want that only SingleCall1 and SingleCall3 are invoked. Help in correcting the code.
Re: Delegates + Remove method
You have to reference to the same multiExecution delegate which you combined in button1.click.
To do that, you can declare the delegate variables with class scope. Try this:
Code:
Dim multiExecution As BeginingDelegate
Dim Call1 As BeginingDelegate
Dim Call2 As BeginingDelegate
Dim Call3 As BeginingDelegate
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Call1 = AddressOf SingleCall1
Call2 = New BeginingDelegate(AddressOf SingleCall2)
Call3 = New BeginingDelegate(AddressOf SingleCall3)
multiExecution = CType([Delegate].Combine(Call1, Call2, Call3), BeginingDelegate)
multiExecution.Invoke()
End Sub
'USE REMOVE METHOD
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim delegateRemoved As BeginingDelegate = CType([Delegate].Remove(multiExecution, Call2), BeginingDelegate)
delegateRemoved.Invoke()
End Sub
Re: Delegates + Remove method
hi stanav,I m getting the error Object reference not set to an instance of an object.
Re: Delegates + Remove method
You have to click button1 first so that you combine call1, call2 and call3 into the multiExecution delegate. After that, you click button2 to remove one of the delegate from the list.
If you launch your app and click button2 right away, of course you will get a null exception because your multiExecution delegate is not yet initialized.
Re: Delegates + Remove method
Sir i m just asking that only na,How to initialize it on Button2 click