Delegate Multicasting

This blog will give you basic knowledge of delegate multicasting. It will also demonstrate you that we can add one or more methods to the delegate and invoke them in single call. We can add or assign more than one methods to delegate by using "+" operator. We can also exclude the method from delegate by using "-" operator.
 
Basics of delegates

Signatures and return type should be same for the delegate and its pointed method. 
 
Focus on 
  • How to declare the delegate?
  • How to assign the method to the delegate?
  • How to assign more than one methods to the delegate?
  • If we implement multicasting, then which method returns the value, we will get?
    1. class Program  
    2. {  
    3.     delegate string Dgate(string str);  
    4.     static Dgate objDgate;  
    5.     static void Main(string[] arg) {  
    6.         // As you can see we assigned the mulitple functions to the delegate like ReplaceSpaces, Reverse, RemoveSpaces.    
    7.         // And we invoke the delegate then it calls all the method that it contained in the same index as we added    
    8.         objDgate = ReplaceSpaces;  
    9.         objDgate += Reverse;  
    10.         objDgate += RemoveSpaces;  
    11.         string ret = objDgate.Invoke("Baljinder Singh");  
    12.         //ret = objDgate("Parminder Pal Singh");// we can also call the delegate like this    
    13.         Console.WriteLine("");  
    14.         Console.WriteLine("--------- Last method returned value ---------");  
    15.         Console.WriteLine(ret);  
    16.         Console.ReadLine();  
    17.     }  
    18.     static string ReplaceSpaces(string s) {  
    19.         Console.WriteLine("Replacing space with hyphen ....");  
    20.         return s.Replace(' ''-');  
    21.     }  
    22.     static string RemoveSpaces(string s) {  
    23.         string temp = "";  
    24.         Console.WriteLine("Removing spaces ....");  
    25.         for (int i = 0; i < s.Length; i++) {  
    26.             if (s[i] != ' ') {  
    27.                 temp += s[i];  
    28.             }  
    29.         }  
    30.         return temp;  
    31.     }  
    32.     static string Reverse(string s) {  
    33.         string temp = "";  
    34.         Console.WriteLine("Reversing string ....");  
    35.         for (int i = s.Length - 1; i >= 0; i--) {  
    36.             temp += s[i];  
    37.         }  
    38.         return temp;  
    39.     }  
    40.     static string Reverse2(string s) {  
    41.         string temp = "";  
    42.         Console.WriteLine("Reversing string2 ....");  
    43.         int i, j;  
    44.         for (j = 0, i = s.Length - 1; i >= 0; i--, j++) {  
    45.             temp += s[i];  
    46.         }  
    47.         return temp;  
    48.     }  
    49. }
Ebook Download
View all
Learn
View all