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?
- class Program
- {
- delegate string Dgate(string str);
- static Dgate objDgate;
- static void Main(string[] arg) {
-
-
- objDgate = ReplaceSpaces;
- objDgate += Reverse;
- objDgate += RemoveSpaces;
- string ret = objDgate.Invoke("Baljinder Singh");
-
- Console.WriteLine("");
- Console.WriteLine("--------- Last method returned value ---------");
- Console.WriteLine(ret);
- Console.ReadLine();
- }
- static string ReplaceSpaces(string s) {
- Console.WriteLine("Replacing space with hyphen ....");
- return s.Replace(' ', '-');
- }
- static string RemoveSpaces(string s) {
- string temp = "";
- Console.WriteLine("Removing spaces ....");
- for (int i = 0; i < s.Length; i++) {
- if (s[i] != ' ') {
- temp += s[i];
- }
- }
- return temp;
- }
- static string Reverse(string s) {
- string temp = "";
- Console.WriteLine("Reversing string ....");
- for (int i = s.Length - 1; i >= 0; i--) {
- temp += s[i];
- }
- return temp;
- }
- static string Reverse2(string s) {
- string temp = "";
- Console.WriteLine("Reversing string2 ....");
- int i, j;
- for (j = 0, i = s.Length - 1; i >= 0; i--, j++) {
- temp += s[i];
- }
- return temp;
- }
- }