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.

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:

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

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

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:

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

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

 
GeneralIntroduction Pinmembermarxxx12-Dec-08 23:23 
Generalgreat great great article Pinmemberanand.lv4-Dec-08 0:43 
GeneralGREAT ARTICLE but, has an Error Code Pinmemberjinfrics28-Apr-08 20:04 
GeneralThat's the best article on Delegates I've found PinmemberFlying--Kiwi6-Apr-07 0:45 
GeneralRe: That's the best article on Delegates I've found PinmemberAlireza . Shirazi6-Apr-07 5:10 
GeneralNice article Pinmemberotterx12-May-06 4:22 
GeneralRe: Nice article PinmemberAlireza . Shirazi11-Mar-07 1:45 
QuestionWhat's The diference ? Pinmemberzaharia_dev22-Feb-06 7:46 
AnswerRe: What's The diference ? PinmemberMartin Tens23-Feb-06 4:07 
QuestionAnd Next ? Pinmemberzard_zhoubeh21-Feb-06 7:34 

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 | Mobile
Web02 | 2.8.140721.1 | Last Updated 17 Feb 2006
Article Copyright 2006 by Alireza . Shirazi
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid