What is a delegate?

Answer Posted / kiran

Delegate is a class that can hold a reference to a method
or a function.Delegate class has
a signature and it can only reference those methods whose
signature is compliant with the
class.Delegates are type-safe functions pointers or
callbacks.
Below is a sample code which shows a example of how to
implement delegates.
Public Class FrmDelegates
Inherits System.Windows.Forms.Form
Public Delegate Sub DelegateAddString()
Private Sub FrmDelegates_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub AddString()
lstDelegates.Items.Add(“Running AddString() method”)
End Sub
Private Sub cmdDelegates_Click(ByVal sender As
System.Object,
ByVal e As System.EventArgs) Handles cmdDelegates.Click
Dim objDelegateAddString As DelegateAddString
objDelegateAddString = AddressOf AddString
objDelegateAddString.Invoke()
End Sub
End Class
In the above there is a method called “AddString()” which
adds a string to a listbox.You
can also see a delegate declared as :-
Public Delegate Sub DelegateAddString()
This delegate signature is compatible with the “AddString”
method.When i mean
compatibility that means that there return types and
passing parameter types are same.Later in command click of
the button object of the Delegate is created and the method
pointer
is received from “AddressOf ” keyword.Then by using
the “Invoke” method the method
is invoked.

Is This Answer Correct ?    1 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is public void in c#?

494


What's the difference between abstraction and encapsulation?

442


What are variables in c#?

471


What are extension methods and where can we use them?

435


What is private static in c#?

464






What is difference between private and static constructor?

445


What is access modifier in c#?

466


How can an inner class access the members of outer class?

524


What is byte c#?

432


what is the Difference between the public and private ?

494


What is the difference between virtual method and abstract method?

525


what is difference between is and as operators in c#?

506


How to implement an object pool in c#.net.

522


What are the advantages of generics in c#?

474


Can non-default constructors be used with single call sao?

502