3

Possible Duplicate:
when & why to use delegates?

I understand most of C# syntax, and I partially understand delegates, but I cannot find any case I would need to use them.

Can you help me understand their place in software development usong some examples? I would be very happy. Thank you.

Community
  • 1
  • 1
Josell
  • 1,924
  • 3
  • 13
  • 20

2 Answers2

1

Delegates are another way of expressing mutual obligations between a code provider and a code consumer.

It's like "I need someone who can add two ints and returns two ints" and "Hey, I am a method and I can add two ints and I return an int, you can use me".

From a distant point of view then, asking "why do I need delegates" is like asking "why do I need interfaces". Just instead of expressing "class contract" you express "method contract".

What's interesting is that most cases handled with delegates can be handled with interfaces and vice versa. It's just that C# gives you more flexibility in chosing between two mechanisms. You don't have such flexibility in Java for example, where obligations are expressed using interfaces.

Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
  • I love interfaces. So, delegates are like interfaces for individual methods? Of course, they act more like a queue of methods to call, but that's the idea, right? – Josell Aug 10 '12 at 16:40
  • Yes, that's the idea. And yes, there are multidelegates (delegates combined) but the basic structure is just "an obligation expressed at method level". – Wiktor Zychla Aug 10 '12 at 16:50
1

One function of a delegate is to act as a function pointer. In a case of a program I had to make, I needed to run similar functions and call them in an array style.

For example, if you had a few functions.

double play(int data1, int data2)
double work(int x, int y)

Those two have the same signature. They both return doubles, and the both take 2 ints. They could by called with a delegate

delegate double myFunctions(int a, int b);

So lets say I needed to run "play" and "work" from the same function. I could do it like this:

public void do_something( myFunctions action, String information)
{
   int input1;
   int input2;
   /*
     Lets say the string was.... the dimensions of a rectangle expressed as 5x8
     here we parse the string so...

     information is "5x8:
     set input1 to 5
     set input2 to 8
   */

   //then run the function that was passed in.
   action(input1, input2);
}

And you would call this function like:

do_something(play, "5x8");
//or
do_something(work, "484x237");

And the comment area there is what I think would make this not a trivial example. Basically, at least in this context, it can help for modularizing programs.

Xantham
  • 1,829
  • 7
  • 24
  • 42