Click here to Skip to main content
11,477,625 members (72,472 online)
Click here to Skip to main content

A Beginner's Guide to Delegates

, 29 Mar 2006 372.9K 5.2K 174
Rate this:
Please Sign up or sign in to vote.
An article on delegates in .NET.

Introduction

In this article, I've covered a brief introduction about delegates. This can be a good 'Beginner's Guide' to delegates.

Background

Here, I assume you have a basic knowledge of function pointers. Because, in the introductory part, I compare delegates with function pointers. For basic ideas on function pointers, please refer this link.

Simple Delegate

A delegate is very much like a C/C++ 'function pointer' or a 'typedef that represents the address of a function'. In C/C++, the address of a function is just a memory address. The C/C++ function pointer holds only the address of a function. This address doesn't carry any additional information, such as the number of parameters expected by the function, types of parameters it takes etc. In fact, this all makes a function pointer type unsafe. Traditionally, calling a function by its address depends on the language supporting the function pointers. And function pointers are inherently dangerous.

Delegates add a safety to the idea of traditional function pointers. The .NET framework has added the bonus of providing a type-safe mechanism called delegates. They follow a Trust-But-Verify model, with automatic verification of the signature by the compiler. Unlike function pointers however, delegates are object-oriented, type-safe, and secured. In short, a delegate is a data structure that refers to a static method or to an object instance, and an instance method of that object. When the delegate references an instance method, it stores not only a reference to the method entry point, but also a reference to the object instance for which to invoke the method.

In VB.NET, we define a delegate using the 'Delegate' keyword. E.g.:

'Defining the delegate 
Public Delegate Sub GreetingDelegate(ByVal MsgString As String)

This does not declare the delegate, it defines it. With this line, we tell the compiler to create a new class called 'GreetingDelegate' that inherits from 'System.Delegate' (the compiler does it automatically for you). This line is equivalent to writing the following code in C/C++:

typedef void (*GreetingDelegate) (char *);

This delegate is only capable of calling a method that takes a String parameter and return nothing. A delegate cares only about the signature of the method you are encapsulating inside of it. So, the function we encapsulate in this delegate (with the appropriate signature) can be invoked safely using this delegate.

Here, I have written two different functions in VB.NET:

Public Sub GoodMoring(ByVal YourName As String)
    Console.WriteLine("Good Morning " + YourName + " !")
End Sub

Public Sub GoodNight(ByVal YourName As String)
    Console.WriteLine("Good Night " + YourName + " !")
End Sub

Now, inside Sub Main, we can create an instance of the delegate, and can assign the address of a function to the delegate. This is done using the AddressOf keyword as follows:

'Instantiating the delegate
Dim MyGreeting As GreetingDelegate

'Here we assign the address of the function we wish to encapsulate
'to the delegate

Console.WriteLine("Adding 'GoodMoring' Reference To A Delegate...")
MyGreeting = AddressOf GoodMoring

Once we assign an address to a delegate, we can use the Invoke method to call the function encapsulated in the delegate.

'Invoking the delegate
Console.WriteLine("Invoking Delegate...")
MyGreeting.Invoke("Mallinath")

Because a delegate cares only about the signature of the method you are encapsulating inside it, we can make it refer to another method also. E.g.:

'Assigning the address of the another function to the same delegate
Console.WriteLine()
Console.WriteLine("Making Existing Delegate To Point To Another Fuction...")
Console.WriteLine("Replacing With Goodnight Reference...")
MyGreeting = New GreetingDelegate(AddressOf Goodnight)

'Another way of invoking the delegate.
Console.WriteLine("Invoking Delegate...")
MyGreeting("Mallinath")

Surprised? Did I forget to put Invoke() there? No! Actually, you don't need to use Invoke(), you can just use the delegate as a proxy for the method.

If you try to assign the address of a method or function not matching the delegate declaration, you'll get a compiler error. Try the following code by putting it in the downloaded source code:

'your existing code goes over here
'add these following lines 
Public Sub BadGreets()
    Console.WriteLine("Wishing You Bad Greetings !")
End Sub

Sub Main()
    'your existing code goes over here
    'add these following lines and try
    MyGreeting = AddressOf BadGreets
    MyGreeting.Invoke("Mallinath")
End Sub

Multicast Delegates

Coming to multicast delegates, these are delegates which are capable of pointing to multiple functions of the same signature. The System.Delegate type maintains a linked list that is used to hold the references to the functions to be invoked by the delegate. This linked list is called as the Invocation List. The delegate class provides a shared member function called Combine(), which adds a reference of specified function to the invocation list.

To demonstrate a multicast delegate, I've added a new function 'GoodEvening', along with the earlier two, to the MulticastDelegate sample program. And I have created separate delegates for each one of the earlier functions.

Public Delegate Sub GreetingDelegate(ByVal MsgString As String)

Public Sub GoodMorning(ByVal YourName As String)
    Console.WriteLine("Good Morning " + YourName + " !")
End Sub

Public Sub Goodnight(ByVal YourName As String)
    Console.WriteLine("Good Night " + YourName + " !")
End Sub

Public Sub GoodEvening(ByVal YourName As String)
    Console.WriteLine("Good Evening " + YourName + " !")
End Sub

In Sub Main, I've instantiated them as:

Dim MorningGreets As GreetingDelegate
Dim EveningGreets As GreetingDelegate

MorningGreets = AddressOf GoodMorning
EveningGreets = New GreetingDelegate(AddressOf GoodEvening)

To illustrate the multicast delegate, I've combined both the delegates into a single delegate, using the Combine() method as:

Console.WriteLine("Adding 'MorningGreets' And" & _
        " 'EveningGreets' References To A Delegate...")
Dim AllGreets As GreetingDelegate = _
        [Delegate].Combine(MorningGreets, EveningGreets)

Combine() returns a new delegate with the merged invocation list of the function references of the specified delegates. Here, we can add one more function reference to the existing delegate as:

Console.WriteLine("Adding Another" & _ 
    " References To Existing Delegate...")
AllGreets = [Delegate].Combine(AllGreets, _
    New GreetingDelegate(AddressOf Goodnight))

As I wrote, the delegate definition line tells the compiler to create a new class inheriting from the System.Delegate type:

Dim NightGreets As GreetingDelegate =  AddressOf Goodnight

This is equivalent to:

Dim NightGreets As GreetingDelegate
NightGreets = New GreetingDelegate(AddressOf Goodnight)

So, the entire thing can be summed up as:

AllGreets = [Delegate].Combine(AllGreets, _
   New GreetingDelegate(AddressOf Goodnight))

As like a function, to add a function reference to a delegate's invocation list, a delegate class provides a function to remove a function reference from the delegate invocation list.

For example:

Console.WriteLine("Removing 'GoodEvening' Reference...")
AllGreets = [Delegate].Remove(AllGreets, EveningGreets)

An Invoke function call on this multicast delegate will call all the functions whose references are stored in the invocation list of that delegate object.

Finally, while concluding multicast delegates, I can say that, it differs from a regular delegate in that it may contain references to more than just one method. Methods in a multicast delegate are executed synchronously when the multicast delegate is invoked, and in the order in which they are added to the list. If one of the called method raises an exception, then the delegate ceases, and the exception is propagated to the delegate caller.

All of the above code used in this article have been put in the samples. You can download and run it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Malli_S
Software Developer
India India
Hello All !
This is Mallinath S. Karkanti, from India. I'm working as a Software Developer in one of the Middle Scale Company... !

Comments and Discussions

 
QuestionExcellent Pin
inspector12331-Jul-13 4:27
memberinspector12331-Jul-13 4:27 
QuestionBut why ?? Pin
Ahmad Halabi26-May-13 6:03
memberAhmad Halabi26-May-13 6:03 
GeneralMy vote of 5 Pin
hfox19-Mar-13 1:08
memberhfox19-Mar-13 1:08 
QuestionVery Good article on delegates Pin
Sparrowhawk3575923-Feb-13 3:05
memberSparrowhawk3575923-Feb-13 3:05 
AnswerRe: Very Good article on delegates Pin
Malli_S1-Mar-13 5:20
memberMalli_S1-Mar-13 5:20 
GeneralMy vote of 5 Pin
Will Barrows29-Sep-12 8:11
memberWill Barrows29-Sep-12 8:11 
GeneralMy vote of 5 Pin
D-Kishore3-Sep-12 21:07
memberD-Kishore3-Sep-12 21:07 
QuestionMy 5+ Pin
ssd_coolguy21-Aug-12 0:30
memberssd_coolguy21-Aug-12 0:30 
nice article..
ssd_coolguy

AnswerRe: My 5+ Pin
Malli_S21-Aug-12 0:33
memberMalli_S21-Aug-12 0:33 
QuestionHow can we Remove the Newly added Delegare Pin
Sahayapraveen4-Jun-12 22:48
memberSahayapraveen4-Jun-12 22:48 
SuggestionThank you!!!! Pin
Sahayapraveen4-Jun-12 21:57
memberSahayapraveen4-Jun-12 21:57 
QuestionHelpful Pin
Member 798693618-May-12 13:01
memberMember 798693618-May-12 13:01 
QuestionThread Safe Pin
bonnsar20-Mar-12 18:32
memberbonnsar20-Mar-12 18:32 
AnswerRe: Thread Safe Pin
Malli_S20-Mar-12 22:18
memberMalli_S20-Mar-12 22:18 
GeneralRe: Thread Safe Pin
bonnsar20-Mar-12 23:00
memberbonnsar20-Mar-12 23:00 
AnswerRe: Thread Safe [modified] Pin
Malli_S21-Mar-12 3:38
memberMalli_S21-Mar-12 3:38 
GeneralRe: Thread Safe Pin
bonnsar21-Mar-12 20:08
memberbonnsar21-Mar-12 20:08 
GeneralRe: Thread Safe Pin
bonnsar25-Mar-12 14:28
memberbonnsar25-Mar-12 14:28 
AnswerRe: Thread Safe Pin
Malli_S26-Mar-12 21:14
memberMalli_S26-Mar-12 21:14 
GeneralRe: Thread Safe Pin
bonnsar27-Mar-12 21:48
memberbonnsar27-Mar-12 21:48 
AnswerRe: Thread Safe Pin
bonnsar1-Apr-12 22:30
memberbonnsar1-Apr-12 22:30 
AnswerRe: Thread Safe Pin
Malli_S5-Apr-12 4:44
memberMalli_S5-Apr-12 4:44 
GeneralRe: Thread Safe Pin
bonnsar6-Apr-12 14:16
memberbonnsar6-Apr-12 14:16 
GeneralRe: Thread Safe Pin
Malli_S9-Apr-12 21:48
memberMalli_S9-Apr-12 21:48 
GeneralRe: Thread Safe Pin
Will Barrows29-Sep-12 8:24
memberWill Barrows29-Sep-12 8:24 
GeneralRe: Thread Safe Pin
bonnsar30-Sep-12 4:43
memberbonnsar30-Sep-12 4:43 
GeneralMy vote of 5 Pin
manoj kumar choubey5-Mar-12 22:22
membermanoj kumar choubey5-Mar-12 22:22 
GeneralMy vote of 4 Pin
brief11019-Nov-11 20:04
memberbrief11019-Nov-11 20:04 
GeneralMy vote of 5 Pin
Saumitra Kumar Paul1-Jun-11 1:17
memberSaumitra Kumar Paul1-Jun-11 1:17 
GeneralRe: My vote of 5 Pin
Malli_S5-Jul-11 21:56
memberMalli_S5-Jul-11 21:56 
GeneralMy vote of 2 Pin
Kaj Jørgensen29-May-11 11:01
memberKaj Jørgensen29-May-11 11:01 
GeneralRe: My vote of 2 Pin
Malli_S5-Jul-11 21:55
memberMalli_S5-Jul-11 21:55 
GeneralMy vote of 5 Pin
amchimum23-May-11 22:14
memberamchimum23-May-11 22:14 
GeneralMy vote of 5 Pin
Adam Mendoza14-Apr-11 15:02
memberAdam Mendoza14-Apr-11 15:02 
GeneralMy vote of 5 Pin
tiwal11-Apr-11 4:42
membertiwal11-Apr-11 4:42 
GeneralMy vote of 5 Pin
sam viper7-Dec-10 8:13
membersam viper7-Dec-10 8:13 
GeneralMy vote of 5 Pin
newlong6-Dec-10 22:53
membernewlong6-Dec-10 22:53 
Generalgood job......... Pin
santosh d16-Feb-10 21:52
membersantosh d16-Feb-10 21:52 
GeneralSolid explanation Pin
Daniel Kamisnki5-Feb-09 12:48
memberDaniel Kamisnki5-Feb-09 12:48 
GeneralOrder of execution Pin
OmegaThree17-Jul-08 11:30
memberOmegaThree17-Jul-08 11:30 
GeneralExcellent explanation Pin
rlsokoloff3-Oct-07 8:30
memberrlsokoloff3-Oct-07 8:30 
GeneralGood article in simple terms Pin
nsdlsandy7-Aug-07 6:15
membernsdlsandy7-Aug-07 6:15 
GeneralThis is an excellent tutorial. Clear, good examples... Pin
aaava5-Jul-07 16:39
memberaaava5-Jul-07 16:39 
GeneralA good, clear explanation Pin
looseSparks23-Feb-07 5:04
memberlooseSparks23-Feb-07 5:04 
GeneralCool article Pin
dbranca6-Apr-06 12:16
memberdbranca6-Apr-06 12:16 
GeneralExpaination for Beginners Pin
Stewart Badger29-Mar-06 22:55
memberStewart Badger29-Mar-06 22:55 
GeneralRe: Expaination for Beginners Pin
Sara_S30-Mar-06 4:19
memberSara_S30-Mar-06 4:19 
GeneralRe: Expaination for Beginners Pin
Malli_S31-Mar-06 19:05
memberMalli_S31-Mar-06 19:05 
GeneralRe: Expaination for Beginners Pin
BPloe4-Apr-06 4:37
memberBPloe4-Apr-06 4:37 
GeneralRe: Expaination for Beginners Pin
cpayne_stargames19-Apr-06 20:55
membercpayne_stargames19-Apr-06 20:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150520.1 | Last Updated 29 Mar 2006
Article Copyright 2006 by Malli_S
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid