What are the advantages of delegates? [duplicate]

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


Solution 1:

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.

Solution 2:

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<T,bool>] 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
  • They 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)

Solution 3:

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.

Solution 4:

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.

Solution 5:

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:

  • MSDN Tutorial
  • An Introduction to Delegates - MSDN Magazine Article