Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C#
Article

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 156.1K   2.3K   46   21
An article to demonstrate the use of delegates.

Introduction

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:

C#
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:

C#
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:

C#
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.

C#
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);
      break;
    case "TREE":
      sortIt = new Sorter(TreeSort);
      break;
}

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

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

if (SortAndSearch(ref numbers, sortIt, 
         Convert.ToInt32(Console.ReadLine())))
    Console.WriteLine("founded");
else
    Console.WriteLine("Not Founde");
Console.ReadLine();

The method of the second programmer is this:

C#
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!

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


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

Comments and Discussions

 
GeneralMy vote of 4 Pin
Chakravarthy Pandian V31-Aug-10 19:50
professionalChakravarthy Pandian V31-Aug-10 19:50 

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.