What is Delegates?

Posted by Unknown

Delegate is a type Safe Object that can point to another  method(or possibly multiple method) in the application , Which can be invoked at later time.



  Delegate act as an intermediary between an event source and an event  destination.
  A delegate in C# is similar to a function pointer in c or c++.

  There are Two Type of  delegate.


  1. Single cast Delegate
  2. Multi cast Delegate                                   
  A Single Cast Delegate Can call only one function.

  A Multi Cast Delegate Can call more than  one function.

  Delegate are used to pass method as-argument to other methods that are invoked through delegates.

  “Once a delegate is assigned a method , it behave exactly like that method. The delegate method can be used like any .Other  method , which parameter and a return value.”

  Delegate type maintains Three important Information.

  The name of the method on which it make calls.

  Any argument(if any)of this method.

  The Return value(if any)of this method.

  Function pointer using Delegate.

  Delegate wrap a method.calling delegate result in calling the method.

  Delegate is a type of object very similar to classes.

  Delegate gives a name to a method signature.

  Declaration Of delegate


public delegate intSumPtr(intx,int y);

       Method of delegate.

int  Add(intx,int y)
          {
returnx+y;
                }
use a delegate to call this method.
SumPtrsPtr= new Sumptr(Add);
Console.WriteLine(sPtr(34,6));


  Example Of Delegate

Using System;
Namespace Akadia.BasicDelegate
{
public delegate void simpledelegate();   //Declaration
classTestDelegate
    {
                public static void MyFunc()
        {
                Console.WriteLine(“I was called by delegate”);
}
Public static void main()
{
                SimpleDelegateSimpleDelegate=new  SimpleDelegate(MyFunc);   //Instantiation
                SimpleDelegate();     //Invocation
}


0 comments:

Post a Comment