Using Delegates To Do The Work

Sometimes there needs to be logic that someone on the outside using your object can do.  For instance, there is a piece of calculation that only the subscriber of the class can use.  Instead of using inheritance and the template method approach, it's also possible to perform some of this through a delegate.  Simply creating a delegate as such:

public delegate float CalculateValueHandler(Account account, MortgateRate rate);

Allows the code to do this:

public void Calculate(MortgageRate rate, CalculateValueHandler handler)
{
  Accounts accounts = AccountService.LoadAccounts();
  foreach (Account account in accounts)
    account.Estimate = handler(account, rate);

  this.SaveChanges();
}

This may not be the most practical example, but delegates can be more useful than inheritance in certain situations.

Comments

No Comments