September 23, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

.NET Delegates: Modern-Day Callback Methods

  • December 9, 2004
  • By Mark Strawmyer
  • Send Email »
  • More Articles »

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

I've modified the previous sample to demonstrate the use of multicast delegates. It involves nothing more than associating another method for callback. The following example includes another method that displays the processed date after the loan is processed and the credit score is displayed:

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.



Click here for a larger image.

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.

Future Columns

The topic of the next column is yet to be determined. If you have something in particular that you would like to see explained here, you can reach me at mstrawmyer@crowechizek.com.

About the Author

Mark Strawmyer (MCSD, MCSE, MCDBA) is a senior architect of .NET applications for large and mid-sized organizations with Crowe Chizek in Indianapolis, Indiana. He specializes in architecture, design, and development of Microsoft-based solutions. Mark was honored to be named a Microsoft MVP for application development with C#. You can reach Mark at mstrawmyer@crowechizek.com.





Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel