Click here to Skip to main content
15,301,841 members
Articles / Programming Languages / C#
Posted 17 Feb 2006


46 bookmarked

How to use delegates in C# - step 1

Rate me:
Please Sign up or sign in to vote.
4.82/5 (52 votes)
17 Feb 20063 min read
An article to demonstrate the use of delegates.


This article helps you to understand delegates in .NET and prepares you to use them later in events.

Using the code

To use the code, first download the article source, then open Visual Studio .NET and create a new Console project using the File menu. Then copy and paste the source code in it.

Delegates are simply function pointers! I think you must be saying "Hmmm, and what's a function pointer?" And I say, "Hold on, I'll tell you".

Function pointers were born in C++. Suppose you're a programmer and a manager of a team. One programmer has written code for sorting an array and he has divided his functionality into various methods like binary sort, quick sort, and …..

Another programmer has written a method to search a number in the array but he needs the array sorted.

As the manager, you're the one who decides in which way the array should be sorted. As you probably know, each sorting method maybe very quick in a specific situation and maybe very time consuming in another situation. Anyway, the algorithm of this program is you must define an array, and give it to the second programmer and tell him how to sort it (with the methods that the first programmer has written), and search a number in it. OK?

Now, what is the problem? As you undoubtedly guessed, the problem is how to tell the second programmer the method to be used for searching. You may not tell him the name of the sorting method. So, what do you do?

You need a function pointer!!! You need an element that can hold the address of the appropriate method and then, just pass that pointer to the second programmer. The second programmer will use that pointer to execute the appropriate method.

Let me tell you that a function pointer can not point to any method! It just can point to specific ones that follow a certain pattern. When you declare the function pointer, you specify the pattern of the methods that this pointer can point to.

Let's talk about delegates now! As I said at the beginning of the topic, delegates are simply function pointers. They hold the address of a function or a method.

For example, you have an array like this:

int[] numbers = new int[] { 5, 9, 10, 3, 7, 2, 6, 1, 4, 8, 0 };

And you have these methods written by the first programmer:

static void BinarySort(ref int[] numbers)
  //Some Codes to sort the array with Binary algoritm
  //Finally, The array will be something like this :
  numbers = new int[] { 0,1,2,3,4,5,6,7,8,9,10};

static void QuickSort(ref int[] numbers)
  //Some Codes to sort the array with Quick algoritm
  //Finally, The array will be something like this :
  numbers = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

static void TreeSort(ref int[] numbers)
  //Some Codes to sort the array with Tree algoritm
  //Finally, The array will be something like this :
  numbers = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

Now, you need to declare a delegate that can point to these methods. You define that just like this:

delegate void Sorter(ref int[] num);

This code means that you have declared a delegate that can point to the methods that have no return value, and it accepts an integer array as parameter and the array is called by reference.

This code will ask the method of sorting and initialize the delegate and then associate the appropriate method to the delegate.

Console.WriteLine("Please Enter a method" + 
     " for Sorting\n(Binary/Quick/Tree)?");

//Consider Binary Search as default
Sorter sortIt = new Sorter(BinarySort);;

switch (Console.ReadLine().ToUpper())
    case "QUICK":
      sortIt = new Sorter(QuickSort);
    case "TREE":
      sortIt = new Sorter(TreeSort);

Then simply call the method that the second programmer has written:

Console.WriteLine("Please Enter a Number to search");

if (SortAndSearch(ref numbers, sortIt, 
    Console.WriteLine("Not Founde");

The method of the second programmer is this:

static bool SortAndSearch(ref int[] numbers, 
                          Sorter srt,int member)
    srt(ref numbers);

    foreach (int i in numbers)
        if (i == member)
            return true;
    return false;

As you see, it gets the array of numbers and a delegate instance and a number to search. It's important that you notice that this method does not know anything about search methods. It just knows that it must call a method which the delegate instance points. And it knows that the method has no return value and has an array of integer as the start parameter.

That's it. I think that's enough. Now try it and try to write some code to practice how to use delegates. And please wait for the second step of this article.

Good luck!


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


About the Author

Alireza . Shirazi
Web Developer
Iran (Islamic Republic of) Iran (Islamic Republic of)
Alireza Shirazi
C#, ASP.Net,AJAX, Elearning

Comments and Discussions

GeneralBest article on Delegates. Pin
Kishor Shivane12-Jun-11 18:33
MemberKishor Shivane12-Jun-11 18:33 
GeneralMy vote of 5 Pin
hsr21079-Feb-11 6:33
Memberhsr21079-Feb-11 6:33 
GeneralMy vote of 4 Pin
Chakravarthy Pandian V31-Aug-10 19:50
professionalChakravarthy Pandian V31-Aug-10 19:50 
QuestionWhere is a second step? Pin
1ten0.0net113-May-10 1:46
Member1ten0.0net113-May-10 1:46 
AnswerRe: Where is a second step? Pin
Amir Mohammad Nasrollahi9-Aug-13 21:04
professionalAmir Mohammad Nasrollahi9-Aug-13 21:04 
GeneralAwesome article Pin
d_uklid27-Apr-10 6:46
Memberd_uklid27-Apr-10 6:46 
GeneralVery Good One.... Pin
Oren Gatgno5-Jan-10 22:07
MemberOren Gatgno5-Jan-10 22:07 
Generalvery good article Pin
Kiran Kumar Veerabatheni29-Oct-09 4:21
MemberKiran Kumar Veerabatheni29-Oct-09 4:21 
Generalgreat article! Pin
alejandro29A20-Oct-09 8:33
Memberalejandro29A20-Oct-09 8:33 
Generalgreat Pin
emil30028-Apr-09 4:22
Memberemil30028-Apr-09 4:22 
GeneralIntroduction Pin
User 466071112-Dec-08 23:23
MemberUser 466071112-Dec-08 23:23 
Generalgreat great great article Pin
anand.lv4-Dec-08 0:43
Memberanand.lv4-Dec-08 0:43 
GeneralFine Article Brother! [modified] Pin
Ummar Muhammad19-Aug-08 1:33
MemberUmmar Muhammad19-Aug-08 1:33 
GeneralGREAT ARTICLE but, has an Error Code Pin
jinfrics28-Apr-08 20:04
Memberjinfrics28-Apr-08 20:04 
GeneralThat's the best article on Delegates I've found Pin
Flying--Kiwi6-Apr-07 0:45
MemberFlying--Kiwi6-Apr-07 0:45 
GeneralRe: That's the best article on Delegates I've found Pin
Alireza . Shirazi6-Apr-07 5:10
MemberAlireza . Shirazi6-Apr-07 5:10 
GeneralNice article Pin
walt_bael12-May-06 4:22
Memberwalt_bael12-May-06 4:22 
GeneralRe: Nice article Pin
Alireza . Shirazi11-Mar-07 1:45
MemberAlireza . Shirazi11-Mar-07 1:45 
QuestionWhat's The diference ? Pin
zaharia_dev22-Feb-06 7:46
Memberzaharia_dev22-Feb-06 7:46 
AnswerRe: What's The diference ? Pin
Martin Tens23-Feb-06 4:07
MemberMartin Tens23-Feb-06 4:07 
QuestionAnd Next ? Pin
zhoubeh21-Feb-06 7:34
Memberzhoubeh21-Feb-06 7:34 

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

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