Delegates, plug-in methods and multicast with delegates in C#

Goud.Kv
Posted by in C# category on for Intermediate level | Points: 250 | Views : 4150 red flag
Rating: 5 out of 5  
 1 vote(s)

C# is an Object-oriented programming language. C# comes with simplicity, expressiveness and great performance to meet the programmer productivity.
Recommendation
Read Co-variance and Contra-variance in C# before this article.

Introduction

So far, we have learnt co-variance and contra-variance in C#. Now lets study about delegates and its properties in this chapter.

Objective

The main objective of this article is to learn delegates, writing plug-in methods with delegates and multicast delegates in C# programming.

Delegates

Delegates are the special types used to refer the methods. In other words, a delegate is an object which is capable for calling a method. Delegate defines the return and parameter types of a particular method.

We have already studied delegates in generic delegates briefly.

By using delegates, we can pass methods (as arguments) to other methods.

Let's have a simple program of using delegate,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Example
{
    class Program
    {
        delegate int Shape(int s);    // declaring delegate

        static int SquareBox(int b)   // static method
        {
            return b * b;
        }

        static void Main()
        {
            Shape sq = SquareBox;     // creating instance to the delegate
            int myBox = sq(4);        // invoking delegate instance
            Console.WriteLine(myBox); // prints 16 
        }
    }
}
In the above program, we have a delegate Shape(). It is clearly shown creating instance to the delegate in the Main() method.

We are directly referring a static method "SquareBox()" from the delegate "Shape()". Hence by using delegates, we can make method objects.

Note: Please read comments in the programs to understand better.

Output of the above program will be,


Delegates are used for event handlers to specify the handler type.

Lambda expressions are used to make the complex delegates more simple.

Plug-in methods

In order to write the plug-in methods, our delegate variable must be assigned to a method at run-time. That is like in the below program,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Example
{
    public delegate int Changer(int a);  // declaring delegate variable

    class DelClass                       // class
    {
        public static void Change(int[] val, Changer c) // This is our utility method
        {                                               // Observe the delegate parameter 'c' in this method
            for (int i = 0; i < val.Length; i++)
                val[i] = c(val[i]);
        }
    }

    class Program
    {
        static int Square(int s)         // static method
        {
            return s * s;                // logic for finding area
        }

        static void Main()
        {
            int[] vals = { 2, 3, 4, 5 };   // integer array
            DelClass.Change(vals, Square); // Calling the utility method

            foreach (int items in vals)    // logic to print the area's of items.
            {
                Console.WriteLine(items);
            }
        }
    }
}
In the above code, we have a delegate variable Changer() with an integer parameter a. And we have a method (utility method) named Change() with two parameters.

Observe that, the method Change() has the delegate parameter Changer() which is needed to specify a plug-in transform.

We also have a static method Square() which has the logic to find the area of a square.

Now, in the main method, we are invoking the method Change() with 'vals' (integer array) and Square() (as plug-in method).

foreach logic is used to loop through the integer array 'vals' and print result for each item in the console.

This program will prints the following lines in your console,


Multicast

Multicast is the special feature of delegates and it is capable for all the delegate instances. In other words, a delegate instance can be referred to the multiple methods. 

'+' and '+=' operators are used to add new method to delegate instance.

'-' and '-=' operators are used to remove any method from the instance.

Let's have a simple program which demonstrates multicast delegates,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Example
{
    class Program
    {    
        public delegate void MultiCast();                                  // delegate

        static void FirstMethod() { Console.WriteLine("First Method"); }   // Method 1
        static void SecondMethod() { Console.WriteLine("Second Method"); } // Method 2
        static void ThirdMethod() { Console.WriteLine("Third Method"); }   // Method 3

        static void Main()
        {
            // Creating instance to the delegate and refering it to the First Method
            MultiCast m = FirstMethod;

            m += SecondMethod;   // Targeting the same instance to the Second Method
            m = m + ThirdMethod; // Refering the same to the Third Method (another way)

            m.Invoke();          // Invoking m calls all the three methods

            Console.WriteLine('\t');

            m = m - FirstMethod; // Removing the First Method from the delegate instance
            m = m - ThirdMethod; // Removing the Third Method from the delegate instance

            m.Invoke();          // Invoking m only calls the Second Method
        }
    }
}
In the above program, we have a delegate variable MultiCast(). And three methods FirstMethod(), SecondMethod() and ThirdMethod().

In the Main() method, we have created instance 'm' for MultiCast() and referred to the FirstMethod()

In the next line, we have targeted the same instance to the SecondMethod(). After that ThirdMethod() is also referred by the delegate instance 'm'.

Now, invoking the delegate instance 'm' will go and call the all three methods and executes them in the order they are added.

Similarly, we can remove the references to the methods by using '-' or '-=' operators like in the program. In our program, we removed reference to FirstMethod() and ThirdMethod().

Now invoking 'm' only calls the SecondMethod().

This is how multicast delegates help in C#.

Observe the output in the console which looks like,


Conclusion

In this article, we have studied delegates with writing plug-in methods and multicast delegates. Hope you understand.

Thanks for reading,

Regards,
Krishna.
Recommendation
Read Differences between delegates and interfaces in C# after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Goud.Kv
Full Name: Krishna Vamshi Goud
Member Level: Gold
Member Status: Member,MVP
Member Since: 2/12/2014 2:34:09 AM
Country: India
Thanks & Regards, Krishna


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)