Delegates in .NET

Delegates

Introduction
            In this article, i am going to discuss about Delegates and how to use a delegate other than event handling. 
            
What is a Delegate?
            Delegate is described as a TYPE SAFE FUNCTION POINTER (A Function Pointers are pointers, i.e. variables, which point to the address of a function). A delegate object is used to hold the address(reference) of a function.

How to Use?

To create and use a delegate we have to follow 3 steps. 

1. Declaration
2. Instantiation
3. Invocation

Steps to Create a delegate

1. Declaration:

Syntax (C#)

delegate result-type Name-of-the-delegate([parameters])

for eg. 
        public delegate void MyDelegate();
  
This will holds the address of any functions, which has no return type and no parameters
    
        public delegate int MyParamDelegate(int param1, string param2);

This will holds the address of any function, which has return type as integer and accepts two parameters ( integer and string)

2. Instantiation:

Inside the class you can instantiate a delegate as like creating a instance to the class. But there are lot of difference between the class instantiation and Delegate instantiation

Syntax (C#)
       delegate-name instance-name = new delegate-name(function-name);

For eg.
        // Declaration 
        public delegate void MyDelegate();
        .
        .
        .
        // Instantiation – inside the class
        MyDelegate delObj = new MyDelegate(MyFunc);
        .
        .
        .
        // MyFunction Definition
        public static void MyFunc()
        {
                // Code here
        }

Please note that the signatures of the myFunc and MyDelegate are matching. i.e., myFunc doesn’t have any return type and parameters similar to MyDelegate.

You can pass static method as well as instant method. In the case of instant method, you have to pass like instance-name.myFunc()

3. Invocation:

delObj() – the invocation part is as simple as like invoking a method.

Here is the complete code for a simple delegate example

 

namespace ConsoleHarness
{
    // Step 1. Declaration
    public delegate void MyDelegate();
    class Program
    {
        static void Main(string[] args)
        {
            //Step 2. Instantiation
            MyDelegate delObj = new MyDelegate(MyFunction); 
            //Step 3. Invocation
            delObj();
            Console.ReadLine(); 
         }
        
        // MyFunction which has the same signature as delegate
        public static void MyFunction()
        {
            Console.WriteLine(“Message from MyFunction”); 
        }
    }
}

 

Multicast Delegate:
         It is nothing but a delegate which has references to more than one function. For a multicast delegate, the declaration and invocation are similar to the normal delegate. It differs in instantiation to usual delegate. 

Here is the Instantiation part of Multicast Delegate (C#)

 

//Step 2. Instantiation
MyDelegate delObj = null; 
delObj += new MyDelegate(MyFunction); 
delObj += new MyDelegate(MyFunction2);

 


Please note that delegate object should be initialized with null value is mandatory in C#. Whereas vb.net it is not required.

More Example:

All of us heard / read, that delegates are extensively used in Event handling. So i am not going to explain delegate with Event handling. Instead i choose,  Create a custom Sorting by using a delegate.

namespace ConsoleHarness
 

{
    // Customer Class
    public class Customer
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    // Step 1. Declaration
    public delegate int MyCompare(Customer obj1, Customer obj2);
    class Program
    {
        static void Main(string[] args)
        {
            //Step 2. Instantiation
            MyCompare delCompare = new MyCompare(Compare);
  
            List<Customer> custList = new List<Customer>{ 
                        new Customer{Name=”Anbu”},
                        new Customer{Name= “Manik”},
                        new Customer{Name= “Vidhya”},
                        new Customer{Name= “Agil”}, 
                        new Customer{Name= “Kanchi”} 
                        };
            MySort(custList,delCompare);
            foreach(Customer cust in custList)
            {
                Console.WriteLine(cust.Name); 
            }
            Console.ReadLine(); 
         }
              
        public static void MySort(List<Customer> c,MyCompare delObj)
        {
            bool isSwapped;
            do
            {
                isSwapped = false; 
                for(int i = 0; i < c.Count – 1;i++) 
                {
                    //Step 3. invocation
                    if (delObj(c[i], c[i + 1]) > 0)
                    {
                        var temp = c[i];
                        c[i] = c[i + 1];
                        c[i + 1] = temp;
                        isSwapped = true;
                    }
                }
            } while (isSwapped);  
        }
        // MyFunction which has the same signature as delegate
        public static int Compare(Customer cust1, Customer cust2)
        {
            return cust1.Name.CompareTo(cust2.Name);
        }
    }
}

 

Summary

In this article, i have explained what is a delegate, how to declare and invoking a delegate, multicasting a delegate and a custom sorting method, which uses a delegate.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s