tags:

views:

609

answers:

7
+21  Q: 

What is Delegate?

I am confused that what is the actual role of a delegate? I have been asked this question many times in my interviews, but I don't think that interviewers were satisfied with my answer.

Can anyone tell me the best definition, in one sentence, with a practical example ?

Thanks

+24  A: 

I like to think of a delegate as "a pointer to a function". This goes back to C days, but the idea still holds.

The idea is that you need to be able to invoke a piece of code, but that piece of code you're going to invoke isn't known until runtime. So you use a "delegate" for that purpose. Delegates come in handy for things like event handlers, and such, where you do different things based on different events, for example.

Here's a reference for JAVA you can look at: http://www.cutthecrap.biz/software/delegates.html

In C#, for example, let's say we had a calculation we wanted to do and we wanted to use a different calculation method which we don't know until runtime. So we might have a couple calculation methods like this:

public static double CalcTotalMethod1(double amt)
{
    return amt * .014;
}

public static double CalcTotalMethod2(double amt)
{
    return amt * .056 + 42.43;
}

We could declare a delegate signature like this:

public delegate double calcTotalDelegate(double amt);

And then we could declare a method which takes the delegate as a parameter like this:

public static double CalcMyTotal(double amt, calcTotalDelegate calcTotal)
{
    return calcTotal(amt);
}

And we could call the CalcMyTotal method passing in the delegate method we wanted to use.

    double tot1 = CalcMyTotal(100.34, CalcTotalMethod1);
    double tot2 = CalcMyTotal(100.34, CalcTotalMethod2);
    Console.WriteLine(tot1);
    Console.WriteLine(tot2);
dcp
+1 for the nod to the simple but effective function pointer in C.
Aiden Bell
It is very nice. Waiting for some other answers also. Thanks
NAVEED
One question related to your answer. How is it really different from calling a function in normal way? Just because of that it is not known at runtime ?
NAVEED
@NAVEED - refer to my latest edit, I included an example. As far as the actual method call, it doesn't look any different from a normal method call in my example above (the calcTotal(amt) is calling the delegate), but the power of delegates is that you can use them as parameters, etc. when you want a method to be able to have different behavior. There are many other things you can use them for also, this is just a simple example. Hope that helps.
dcp
It's not known at runtime, and is a bound function rather than a free function - assigning a non-static method `Foo` to a delegate will call `this.Foo()` rather than a static function as a function pointer would do ( in C, you often have an extra `void*` parameter to pass `this` to the function pointer )
Pete Kirkham
It is really helpful. Thanks.
NAVEED
+3  A: 

Wikipedia has a good article on the delegation pattern with simple and complex examples in java and php.

Asaph
+7  A: 

a delegate is simply a function pointer.
simply put you assign the method you wish to run your delegate. then later in code you can call that method via Invoke.

some code to demonstrate (wrote this from memory so syntax may be off)

delegate void delMyDelegate(object o);

private void MethodToExecute1(object o)
{
    // do something with object
}

private void MethodToExecute2(object o)
{
    // do something else with object
}

private void DoSomethingToList(delMyDelegate methodToRun)
{
    foreach(object o in myList)
        methodToRun.Invoke(o);
}

public void ApplyMethodsToList()
{
    DoSomethingToList(MethodToExecute1);
    DoSomethingToList(MethodToExecute2);
}
Mladen Prajdic
Your answer is also very helpful but answer with more votes is accepted. Thanks for your response.
NAVEED
+3  A: 

Think about delegate as about a simplified implementation of Command pattern.

Vitaliy Liptchinsky
+3  A: 

Taken from here

Q What are delegates?
A When an object receives a request, the object can either handle the request itself or pass the request on to a second object to do the work. If the object decides to pass the request on, you say that the object has forwarded responsibility for handling the request to the second object.

Or, as an easy pseudo example: something sends a request to object1. object1 then forwards the request and itself to object2 -- the delegate. object2 processes the request and does some work. (note: link above gives good examples)

Anthony Forloney
It is also very nice way to teach. Thanks.
NAVEED
+2  A: 

While not really a "function pointer", a delegate might look like this is a dynamic language like PHP:



$func = 'foo';
$func();

function foo() {
    print 'foo';
}

or in JavaScript you could do something like:


var func = function(){ alert('foo!'); }
func();

mmattax
+1  A: 

A great explanation and practical implementation of the Delegate pattern can be found in the Google Collections Forwarding Classes (also, the Decorator pattern).

Carl