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.