Friday, September 11, 2015

TYPE OF DELEGATES

Delegates are of two types and depending upon the requirement of the application, the suitable type of delegate is selected. The two types of delegates are:

  1.  Single-cast delegate 
  2. Multicast delegate

 A single-cast delegate can call only one method at a time, whereas a multicast delegate can call multiple methods at the same time.

Single-cast Delegate 

A single-cast delegate derives from the System.Delegate class. It contains reference to only one method at a time. In the preceding code, the delegate used is a single-cast delegate. The WriteConsole() and WriteFile() methods are being referenced by the delegate, PrintData, one after the other at run time. Consider the coffee vending machine example. To provide black coffee, a delegate that holds reference to the methods to dispense hot water and coffee powder is used. The reference to these methods is made dynamically, but one after the other. This means coffee powder and hot water will be dispensed from the machine one after the other.

Multicast Delegate 

A multicast delegate derives from the System.MulticastDelegate class. It contains an invocation list of multiple methods. In multicasting, you create a single delegate that invokes multiple encapsulated methods. Consider the coffee vending machine example. You are dispensing black coffee, which in turn calls the methods to dispense hot water and coffee powder. If you want the methods to dispense hot water and coffee powder to be called at the same time, you can make use of a multicast
delegate.

No comments:

Post a Comment