What are the benefits/advantages of using delegates? Can anyone provide any simple examples?
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.
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.
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:
Delegates serve three purposes:
- A simplified implementation of the Observer pattern
- A simplified implementation of callbacks
- 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.
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)
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?
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.