Multicast Deletages (Multicasting)

Multicasting is the ability to create an invocation list, or chain, of methods that will be automatically called when a delegate is invoked.

Steps:
  • Instantiate a delegate
  • use the + or += operator to add methods to the chain
  • use the or –= operator to remove methods from the chain 
If the delegate returns a value, then the value returned by the last method in the list becomes the return value of the entire delegate invocation. 

Example:

// Multicasting Demo
using System;
// Declare a delegate type
delegate void ModifyString(ref string sTestString);

class MultiCastDemo
{
  // Replaces spaces with dollars
  static void ReplaceSpaces(ref string sTestString)
  { 
    sTestString = sTestString.Replace(' ', '$');
    Console.WriteLine("Replaced spaces with dollars.");
  }
  // Remove spaces
  static void RemoveSpaces(ref string sTestString)
  {
    string temp = "";
    int i;
    for(i=0; i < sTestString.Length; i++)
      if(sTestString[i] != ' ') temp += sTestString[i];
    sTestString = temp;
    Console.WriteLine("Removed spaces.");
  }
  // Reverse a string
  static void Reverse(ref string sTestString)
  {
    string temp = "";
    int i, j;
    for(j=0, i= sTestString.Length-1; i >= 0; i--, j++)
      temp += sTestString[i];
    sTestString = temp;
    Console.WriteLine("Reversed string.");
  }

  static void Main()
  {
    // Construct delegates
    ModifyString oModifyString;
    ModifyString oModifyStringReplaceSpaces = ReplaceSpaces;  // Method Group Conversion
    ModifyString oModifyStringRemoveSpaces = RemoveSpaces;  // Method Group Conversion
    ModifyString oModifyStringReverseString = Reverse;  // Method Group Conversion
    string sString = "This is a test for Multicast Delegates";
   
    // Set up multicast
    oModifyString = oModifyStringReplaceSpaces;
    oModifyString += oModifyStringReverseString;
   
    // Call multicast
    oModifyString(ref sString);
    Console.WriteLine("Resulting string: " + sString);
    Console.WriteLine();
   
    // Remove replace and add remove
    oModifyString -= oModifyStringReplaceSpaces;
    oModifyString += oModifyStringRemoveSpaces;
    sString = "This is a test."; // reset string
   
    // Call multicast
    oModifyString(ref sString);
    Console.WriteLine("Resulting string: " + sString);
    Console.WriteLine();
  }
}

Related Post: Delegates

No comments:

Post a Comment