Monday, 23 September 2013

Delegates in C#.Net


Introduction
  • Delegates are objects which point towards a method which matches its signature(values passed to the method) to that delegate.
  • Delegates are reference type used to encapsulate a method with a specific signature.
  • C++ function pointers are called as C#.NET delegates.
  • Delegates holds the address of one method or addresses of many methods.
  • Delegates hides some information like class names and method names.
  • The delegates are divided into two types, singlecast delegate and multicast delegate.
  • Single cast delegate holds the address of one method, and multicast delegate holds the addresses of many methods.
Steps for creating a delegate: 1. Write a class with a set of methods
Syntax:
class Test
{
    public void print()
    {
        logic;
    }
}
2. Create a delegate
Syntax: 
Public delegate void Dname()
3. Create an object for the delegate with the address of a method
Syntax: 
Test t=new Test();
Dname x=new Dname(t.print);
4. Call the delegate object--> x();
Example on single cast delegates: Open windows forms application project
Place a button
Code in general declaration
    class Test
    {
        public void print()
        {
        MessageBox.Show("from print");
        }//print
        }//test
        public delegate void XYZ();

        private void button1_Click(object sender, EventArgs e)
        {
            Test t = new Test();
            XYZ x = new XYZ(t.print);
            x();
    }
Working with Multicast Delegate:
  • Multicast delegate holds a collection of methods.
  • Multicast delegate holds a sequence of methods.
  • A collection of single cast delegates is also called as Multicast delegate.
  • Multicast delegate supports arithmetic + and - operations.
  • + operator adds a method into the sequence.
  • - operator remove a method from the sequence.
Example on Multicast delegate:
Open console application project.
Code in general declaration(Before main method).
    class program
    {
            class Test
            {
                public void m1()
                {
                    Console.Write("GM");
                }//m1
                public void m2()
                {
                    Console.WriteLine("GA");
                }//m2
            }//test
        }//program
        public delegate void Dname();
        
        static void Main()
        {
            Test t = new Test();
            Dname d1, d2, d3, d4, d5, d6;
            d1 = new Dname(t.m1);
            d2 = new Dname(t.m2);
            d3 = d1 + d2;
            Console.WriteLine("from D3");
            D3();
            D4 = D3 + D3;
            Console.WriteLine("from D4");
            D4();
            D5 = D4 - D1;
            Console.WriteLine("from D5");
            D5();
            D6 = D5 - D3 - D2;
            Console.WriteLine("from D6");
            D6();//Null reference
            Console.ReadKey();
    }
       

No comments:

Post a Comment