Friday, April 26, 2013

Delegate in C#

==>>A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure..

==>>A Delegate is a special type  function means it can point to those function which are having identical signature with delegate.
you can also call delegate as a interface of methods as this acts same as interface in c# but that implemented for classes and this is implemented for methods..





* Step to create a delegate:
1 . Declaration
2. Instantiation
3. Invocation 




* Why we need Delegate.......
  1. We can call many of method by single delegate no need of writ many of function.
  2. We  set up event based system easily.
  3. We can calling many method that in different but having same signature.
  4. We can  passing in parameter field a function. 
  5. we can use select method.

 You take a new console application in visual studio and write the sample code in cs file:---

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication5
{
    public delegate string MyDelegate();//Declaration

    public class TestDelegat
    {
        public string TestMethod()
        {
            return "This is Delegate Sample Program in C#.";

        }

    }

    class Program
    {

        static void Main(string[] args)
        {
            TestDelegat TD = new TestDelegat();
            MyDelegate MDel = new MyDelegate(TD.TestMethod);//Insatantiation
            Console.Write("Output: " + MDel());//Invocation


        }
    }
}


 first we define a delegate name with its signature,in this case its return type is string and no arguments. then we create instance of delegate which is MyDelegate now this can point to (reference to) all those function which having same signature as in our case function is TestMethod() and at the last we invoke this and receive this in message.


The main advantage of delegate is multi cast ...

*For use multi cast we need write this code

In The Class..

  public void TestMethodMulticast()
        {
           console.write("Multicast");

        }


and in the Static Void Main


MyDelegate  TD= null;
            TD+= new MyDelegate  (TD.TestMethod);
            TD+= new MyDelegate  (TD.TestMethodMulticast);



Hope this post will help you for find your solution

Happy Coding



No comments:

Post a Comment