.NET Delegates: Modern-Day Callback Methods
Delegates became more mainstream to the Microsoft programming world when Microsoft included them in the .NET Framework, but they actually have been around in another form for a while. Many programmers will recognize them as callback functions/methods. In fact, a brief discussion regarding the purpose of callback methods before jumping into the specifics of delegates will make delegates easier to understand.
Using Delegates
Delegate sample code
using System;
namespace CodeGuru.Delegates
{
/// <summary>
/// Sample class representing a loan applicant.
/// </summary>
public class LoanApplicant
{
public double CreditScore = 0;
}
/// <summary>
/// Sample class containing a loan processing example.
/// </summary>
public class LoanSystem
{
// Loan applicant.
private LoanApplicant _LoanApplicant = new LoanApplicant();
// Delegate for processing a loan.
public delegate void ProcessLoanDelegate(LoanApplicant
loanApplicant);
// Process the loan application.
public void ProcessLoanApplication(ProcessLoanDelegate
processLoan)
{
// Calculate the credit score
this.CalculateCreditScore(_LoanApplicant);
// Execute the callback method
processLoan(_LoanApplicant);
}
// Calculate the applicant's credit score.
private void CalculateCreditScore(LoanApplicant loanApplicant)
{
Random randNumber = new Random();
loanApplicant.CreditScore = randNumber.Next(100) + .5;
}
}
/// <summary>
/// Sample application to demonstrate the use of delegates.
/// </summary>
class DelegateExample
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
DelegateExample example = new DelegateExample();
LoanSystem loanSystem = new LoanSystem();
loanSystem.ProcessLoanApplication(
new LoanSystem.ProcessLoanDelegate(
example.DisplayCreditScore));
Console.ReadLine();
}
/// <summary>
/// Display the loan applicant's credit score.
/// </summary>
/// <param name="loanApplicant">Loan applicant</param>
public void DisplayCreditScore(LoanApplicant loanApplicant)
{
Console.WriteLine("Applicant Credit Score: {0}",
loanApplicant.CreditScore);
}
}
}
Figure 1. Output from Delegate Sample Code
Multicast Delegates
You may want to have multiple associated methods that are called. This is known as having multicast delegates. When you have multiple methods, .NET automatically builds a list and calls them in the sequence they were assigned.
Multicast delegates sample code
using System;
namespace CodeGuru.Delegates
{
/// <summary>
/// Sample application to demonstrate the use of delegates.
/// </summary>
class DelegateExample
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
DelegateExample example = new DelegateExample();
LoanSystem loanSystem = new LoanSystem();
loanSystem.ProcessLoanApplication(
new LoanSystem.ProcessLoanDelegate(
example.DisplayCreditScore));
loanSystem.ProcessLoanApplication(
new LoanSystem.ProcessLoanDelegate(
example.DisplayProcessingInfo));
Console.ReadLine();
}
/// <summary>
/// Display the loan applicant's credit score.
/// </summary>
/// <param name="loanApplicant">Loan applicant</param>
public void DisplayCreditScore(LoanApplicant loanApplicant)
{
Console.WriteLine("Applicant Credit Score: {0}",
loanApplicant.CreditScore);
}
/// <summary>
/// Display the loan applicant's processing information.
/// </summary>
/// <param name="loanApplicant"></param>
public void DisplayProcessingInfo(LoanApplicant loanApplicant)
{
Console.WriteLine("Loan Processed: {0}",
loanApplicant.ProcessedDate.ToLongDateString());
}
}
/// <summary>
/// Sample class representing a loan applicant.
/// </summary>
public class LoanApplicant
{
public double CreditScore = 0;
public DateTime ProcessedDate;
}
/// <summary>
/// Sample class containing a loan processing example.
/// </summary>
public class LoanSystem
{
// Loan applicant.
private LoanApplicant _LoanApplicant = new LoanApplicant();
// Delegate for processing a loan.
public delegate void ProcessLoanDelegate(LoanApplicant
loanApplicant);
// Constructor
public LoanSystem()
{
}
// Process the loan application.
public void ProcessLoanApplication(ProcessLoanDelegate
processLoan)
{
// Calculate the credit score
this.CalculateCreditScore(_LoanApplicant);
// Set the processing information
_LoanApplicant.ProcessedDate = DateTime.Now;
// Execute the callback method
processLoan(_LoanApplicant);
}
// Calculate the applicant's credit score.
private void CalculateCreditScore(LoanApplicant loanApplicant)
{
Random randNumber = new Random();
loanApplicant.CreditScore = randNumber.Next(100) + .5;
}
}
}
Output from the modified sample looks similar to Figure 2.
Figure 2. Output from Multicast Delegates Sample Code
Uses for Delegates
Delegates can have a number of uses in your applications. The following list contains a rough description of some of the ways you could put delegates to work for you. The list is by no means a complete list, but it should give you an idea of some different areas in which delegates may be appropriate:
- They enable callback functionality in multi-tier applications as demonstrated in the examples above.
- The CacheItemRemoveCallback delegate can be used in ASP.NET to keep cached information up to date. When the cached information is removed for any reason, the associated callback is exercised and could contain a reload of the cached information.
- Use delegates to facilitate asynchronous processing for methods that do not offer asynchronous behavior.
- Events use delegates so clients can give the application events to call when the event is fired. Exposing custom events within your applications requires the use of delegates.
No comments:
Post a Comment