Click here to Skip to main content
Click here to Skip to main content

How to use delegates in C# - step 1

, 17 Feb 2006
Rate this:
Please Sign up or sign in to vote.
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 :

static void TreeSort(ref int[] numbers)
  //Some Codes to sort the array with Tree algoritm
  //Finally, The array will be something like this :

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!



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. Pinmemberportonova12-Jun-11 18:33 
GeneralMy vote of 5 Pinmemberhsr21079-Feb-11 6:33 
GeneralMy vote of 4 PinmemberChakravarthy Pandian V31-Aug-10 19:50 
QuestionWhere is a second step? PinmemberL0\/3M@Ch|n313-May-10 1:46 
AnswerRe: Where is a second step? PinprofessionalAmir Mohammad Nasrollahi9-Aug-13 21:04 
GeneralAwesome article Pinmemberd_uklid27-Apr-10 6:46 
GeneralVery Good One.... PinmemberOren Gatgno5-Jan-10 22:07 
Generalvery good article PinmemberKiran Kumar Veerabatheni29-Oct-09 4:21 
Generalgreat article! Pinmemberalejandro29A20-Oct-09 8:33 
just one mention, function pointers are born in C
Dios existe pero duerme...
Sus pesadillas son nuestra existencia.
(Ernesto Sabato)

Generalgreat Pinmemberemil30028-Apr-09 4:22 



| Advertise | Privacy | Mobile
Web01 | 2.8.140709.1 | Last Updated 17 Feb 2006
Article Copyright 2006 by Alireza . Shirazi
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid