tags:

views:

3206

answers:

7

What are the benefits/advantages of using delegates? Can anyone provide any simple examples?

+14  A: 

They're a great way of encapsulating a piece of code. For instance, when you attach an event handler to the button, that handler is a delegate. The button doesn't need to know what it does, just how to call it at the right time.

Another example is LINQ - filtering, projecting etc all require the same kind of template code; all that changes is the logic to represent the filter, the projection etc. With lambda expressions in C# 3 (which are converted into delegates or expression trees) this makes it really simple:

var namesOfAdults = people.Where(person => person.Age >= 18)
                          .Select(person => person.Name);

(That can also be represented as a query expression, but let's not stray too far from delegates.)

Another way of thinking of a delegate is as a single-method interface type. For example, the EventHandler delegate type is a bit like:

public interface IEventHandler
{
    void Invoke(object sender, EventArgs e)
}

But the delegate support in the framework allows delegates to be chained together, invoked asynchronously, used as event handlers etc.

For more on delegates and events, see my article on the topic. Its focus is events, but it covers delegates too.

Jon Skeet
Thanks John. As a beginner, it is still a little hard to grasp. Sometimes, I think I need to do it the old way before delegates came along to really see the true advantage.
Xaisoft
Oops, sorry I misspelled your name.
Xaisoft
@Xaisoft: Don't worry :) And yes, it can be a little hard to grasp. But it comes over time - and then you wonder what you did before delegates came along, particularly with lambda expressions...
Jon Skeet
Also, for beginners, it's important to realize that delegates don't let you do anything you couldn't do otherwise. It just makes it easier and cleaner (if not abused). Delegates themselves have undergone two revisions since .Net 1.0, and are much more concise now compared to their original form.
Michael Meadows
+2  A: 

Delegate in C# is eqv. to function pointer in C, but it also carries a reference to the class instance that it was created from.

All event handlers in Windows Forms are delegates.

Joshua
+2  A: 

Advantages compared to what? Delegates can be useful things, and surely have their place in a lot of moderately complex C# code. (Whenever you use events in classes you are implicitly using multicast delegates). If you want an introduction to their syntax and uses, I recommend the following articles:

Noldorin
Advantages as far as alternatives used today.
Xaisoft
Oh, I see. Well in C# you don't really have a choice of alternatives. There's no point in using them for the same purpose as events (although it can be done of course). You typically don't use real pointers, as that requires unsafe code, which is considered bad practice and leads to security issues.
Noldorin
@Noldorin I may be misunderstanding your comment, but events use delegates. It's transparent, but it does occur.
Michael Meadows
@Michael: Yeah, that comment was slightly confusing on second look. Events are indeed multicast delegates with syntactic sugar for the most part (plus a few other differences, which have been discussed in other threads). I think I wrote that delegates are implicitly used but then deleted that bit :P
Noldorin
+2  A: 

Delegates serve three purposes:

  1. A simplified implementation of the Observer pattern
  2. A simplified implementation of callbacks
  3. Anonymous (non-reusable) blocks of code

Observer

public class Something
{
    public event EventHandler SomethingHappened;
}

public class SomethingConsumer
{
    private mySomething = new Something();

    public void WireUpEvents()
    {
        mySomething.SomethingHappened += whenSomethingHappened;
    }

    private void whenSoemthingHappened(object sender, EventArgs e)
    {
        // do something
    }
}

CallBack

public void DoSomethingAsynchronously(EventHandler callBack)
{
    // long running logic.
    callBack(this, EventArgs.Empty);
}

Anonymous non-reusable code

public void DoSomethingReusably(Action nonReusableCode)
{
    // reusable code
    nonReusableCode();
    // more reusable code
}

public void DoALotOfSomething()
{
    DoSomethingReusably(() => { /* non-reusable code here */ });
    DoSomethingReusably(() => { /* non-reusable code here */ });
    DoSomethingReusably(() => { /* non-reusable code here */ });
}

In all cases, it's just a matter of providing conciceness.

Michael Meadows
+3  A: 

This is a pretty vague topic, but here are a few things to consider -

Delegates are basically a cleaner, easier function pointer. Any place where function pointers were used in C++, you can think delegate.

Advantages to using them in design:

  • Can lead to easy reuse of code
  • Can provide a great amount of flexibility in your designs
  • Allow you to develop libraries and classes that are easily extensible, since it provides an easy way to hook in other functionality (for example, a where clause in LINQ can use a delegate [Func] to filter on, without having to write new code in the Where method

Potential disadvantages:

  • They ~can~, particularly if used naively, lead to code that is more difficult to read
  • The can introduce behavior into your component that is unexpected, since 3rd party code out of your control will get called (For example, if somebody attaches a delegate to one of your events that causes an infinite loop, it can make your class look bad, even though it has nothing to do with you)
Reed Copsey
+1  A: 

Disclaimer: I'm not saying how I used a delegate is the intended way but it is an example.

I've only used it once before but basically in our app the user clicks a 'Complete' button for a step which then takes them to a routing page to decide where to send it next. So technically the step they just clicked 'Complete' on isn't really finished until they route it. But since I'm on another page I didn't easily have access to where they just were.

So what I did was created a delegate for the few steps that required special processing (in this case an email) when the clicked 'Complete', and when they routed it on the next page I would check for the existance of the delegate and if it was there call it to fire my 'stored' event.

Creative: probably, wrong: maybe, working: definately.

Like I said probably not how it was intended to be used, but coding is as much art as science right?

Jeff Keslinke
Thanks for the example.
Xaisoft
+1  A: 

I remember an early Java GUI framework that had no concept of delegates or command routing. In order to make a button that does something, you had to subclass Button and override the click method. You ended up with lots and lots of UI element subclasses with little bits of your application code in them.

The code that handles that click has to go somewhere, and in an OO language like Java or C# it has to go on a class, but delegates allow it to happen on convenient place. That often leads to having too much code doing too many different things in a form class, but that's a different issue.

Anthony