Delegates in C#


Delegates in C#
Delegates in C# are similar to functional pointers in C++ and are used to encapsulate a method that have similar signature like delegate. We can declare a delegate type with “delegate” keyword in C#. Moving forward, we will see more about delegates and its uses.

Delegates – A Detailed Look
A delegate is a type that references a method once it is assigned to that method and it behaves exactly like that method. The delegate method can be used like any other method, with parameters and return value.
Any method that matches the delegate’s signature, in terms of return type and parameters can be assigned to that delegate.

Some information about Delegates
1.      Delegates have are similar to c++ function pointer but are type safe.
2.      Delegates allow method to be passed as parameters.
3.      Delegates can be used to define callback methods.
4.      Delegate can be chained together for example: multiple methods can be called on a Single event.
5.      .Net2.0 introduced a new stuff called anonymous method delegate.
Example
public delegate void PrintDelegate(String name);

Calling a Named method using delegate
In Named method, we put the reference of the method in delegate and the definition of the methods will lie separately. When we instantiate the delegate then method name is passed as a parameter.
The following Console snippet describes the working of Named Method:
using System;

namespace AstepAhead.namedmethod
{
       public class delegateClass
       {
              public delegate void delegateAdd(int x, int y);
             
              public static void AddNum(int x, int y)
{
       Console.WriteLine(“Sum of {0},{1} = {2}”, x,y,x+y);
}

public static void Main()
{
       Delaget Add myAddDel = new delegateAdd(delegateclass.AddNum);
      
       Console.WriteLine(“Enter first number : “);
       Int num1= int.parse(Console.ReadLine());

       Console.WriteLine(“Enter second number : “);
       Int num2= int.parse(Console.ReadLine());

       //Invoke named method

       myAddDel(num1, num2);
       Console.ReadLine();
}
}
}







Multicast Delegates 
A multicast delegate has a linked list of delegates, called an invocation list, consisting one or more elements. When a multicast delegate is invoked, the delegates in the invocation list are called synchronously in the order which they appear of.  An error occurs during execution of the list then on exception is thrown.

using System;

namespace AStepAhead.MulticastDelegate
{
    public delegate void DelString(string str);

    public class MulticastDelegate
    {
        public static void firstMethod(string x)
       {
           Console.WriteLine("It prints using first method.\nYou have entered:{0}", x);
       }
       public static void secondMethod(string y)
       {
           Console.WriteLine("\nIt prints using second method.\nYou have entered:{0}", y);
       }
       public static void thirdMethod(string z)
       {
           Console.WriteLine("\nIt prints using third method.\nYou have entered:{0}", z);
       }
        static void Main(string[] args)
        {
            Console.Clear();
            Console.Write("Enter string : ");
            string str = Console.ReadLine();
            DelString myMultiDel1, myMultiDel2, myMultiDel3, myMultiDel4, myMultiDel5;
           
            //Firs call method individually
            myMultiDel1 = new DelString(firstMethod);
            myMultiDel1(str);
            Console.ReadLine();
            myMultiDel2 = new DelString(secondMethod);
            myMultiDel2(str);
            Console.ReadLine();
            myMultiDel3 = new DelString(thirdMethod);
            myMultiDel3(str);

            //Combine two delegates or multicast
            Console.WriteLine("\nThis all using Multicast delegates\n");
            myMultiDel4 = myMultiDel1 + myMultiDel2 + myMultiDel3;
            myMultiDel4(str);

            //another way to multicast
            Console.WriteLine("\nThis all using Multicast delegates showing another way of multicasting\n");
            myMultiDel5 = new DelString(firstMethod);
           
            //multicasting or combining / attaching
            myMultiDel5 += new DelString(thirdMethod);
            myMultiDel5(str);

            //deattaching
            myMultiDel5 -= new DelString(firstMethod);
            myMultiDel5(str);

            Console.ReadLine();

       
        }
    }
}


Anonymous method
In Anonymous method, we can write the entire code-block of a method within delegate like a parameter. It eliminates the need to create a separate method.
The Scope of the parameters of an anonymous method is in the anonymous method-block only. In an anonymous method, the use of jump statements like goto, break or continue are not allowed whose target is outside the anonymous method block. It cannot access the ‘ref’ or ‘out’ parameters of an outer scope. Moreover, no unsafe code can be accessed within the anonymous method block.

using System;

namespace AstepAhead.anonymousmethod
{
       public class delegateClass
       {
              public delegate void delegateAdd(int x, int y);
             

              public static void Main()
              {            
              delegatelass mydelcls = new delegateAdd();
              mydelcls.delAdd mydellAdd = new mydelcls.delAdd(int a, int b)
              {

                     Cosole.WrieLine(“Sum of {0}, {1} = {2}”, a,b, b+a);
};     //anonymous block

Console.WriteLine(“Enter first number : “);
Int num1= int.parse(Console.ReadLine());

Console.WriteLine(“Enter second number : “);
Int num2= int.parse(Console.ReadLine());

//Invoke named method

myAddDel(num1, num2);
Console.ReadLine();
}
}
}                  Postec by :CODE DIGEST

Comments

Popular posts from this blog

C# Constructor

Hiding vs Overriding