Tuesday, 24 September 2013

Delegates - C Sharp

A delegate is a type safe function pointer.That is, they hold reference(Pointer) to a function. 

The signature of the delegate must match the signature of the function, the delegate points to, otherwise you get a compiler error. This is the reason delegates are called as type safe function pointers.

A Delegate is similar to a class. You can create an instance of it, and when you do so, you pass in the function name as a parameter to the delegate constructor, and it is to this function the delegate will point to.

Declaration:
A delegate is declared by using the keyword delegate, otherwise it resembles a method declaration.
delegate int delegateAdd(int xint y);

Instantiation:
To create a delegate instance, we need to assign a method (which has same signature as delegate) to delegate.

        static int add(int aint b)
        { 
          return a + b
        }

        //create delegate instance
        delegateAdd objAdd = new delegateAdd(Add);

        //short hand for above statement
        delegateAdd objAdd = Add;

Invocation:
     // Invoke delegate to call method
     int result = objAdd.Invoke(36);

     //short hand for above statement
     int result = objAdd(36); 
Invoking a delegate is like as invoking a regular method.

Complete Code is:
class Program
{
        delegate int delegateAdd(int xint y);

        static int add(int aint b)
        { return a + b; }

        static void Main(string[] args)
        {
           // Program p = new Program();
           //delegateAdd _del = p.add;
            delegateAdd _del = add;
            int result = _del.Invoke(36);
            Console.Write(result);
            Console.Read();
        }
}

Output will be : 9

Type of Delegate
Delegates are one of two types:
  1. Singlecast Delegate
  2. Multicast Delegate
Singlecast DelegateA Singlecast delegate is derived from the System.Delegate class. It can contain a reference for one method at a time. In the above example the delegate uses a Singlecast delegate.

Multicast DelegateA Multicast delegate is derived from the System.MulticastDelegate class. It can contain references for multiple methods. For understanding multicast delegates you can consider the real-life example: of a Coffee vending machine.

A Coffee vending machine has three containers for Milk, Coffee, and Tea. If you press the Tea button then there will two containers, Milk and Tea that work together. And if you press the button for Coffee then the Milk and Coffee containers will work. So if you want to call multiple functions then you can use a multicast delegate.

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

namespace Anonymous
{
    class Class1    {
        public delegate void Vender();

        public static void Milk()
        {
            Console.Write("Milk + ");
        }
        public static void Tea()
        {
            Console.Write("Tea = Tea ");
        }
        public static void Coffee()
        {
            Console.Write("Coffee = Coffee ");
        }

        static void Main()
        {
            Vender vender = new Vender(Milk);
            Console.WriteLine("\t\tPress 1 For Tea\n\t\t Press 2 For Coffee");
            int Opt = Convert.ToInt32(Console.ReadLine());
            switch (Opt)
            {
                case 1:
                    vender += Tea;
                    break;

                case 2:
                    vender += Coffee;
                    break;

                default:
                    Console.WriteLine("Invalid Option !");
                    Environment.Exit(0);
                    break;
            }

            vender();
            Console.ReadKey();
        }
    }
}
In the above program I just created the three functions, Tea, Coffee and Milk. When one is pressed there will be two functions, called Milk and Tea. If the user chooses both then again the two functions, Milk and Coffee are called. Since Milk is common to both situations I just pass Milk in the Delegate parameter. And the delegate understands "+" and "+=" for adding references of functions and "-" and "-=" for removing function references, so depending on the option used I just add a function reference with the same Delegate object vendor. And invoke the delegate vendor.
Remember, multicasting of delegate should have a return type of Void otherwise it will throw a runtime exception.
Anonymous Method In C# 1.0 you can use a delegate and pass a function reference with an initializing delegate with a function name, but C# 2.0 introduced anonymous functions.

Creating an anonymous method as an inline block of code to be passed as a delegate parameter can be done as you see in the 
following: 


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

namespace Anonymous
{
    class Class1    {
        public delegate void Del();

        static void Main(string[] args)
        {
            Del obj = delegate() {
                Console.WriteLine"Class1.fun");
            };

            obj();
        }
    }
}
Use of an anonymous function can reduce the lines of code. So, here in the program above you can see I just passed a block of code for a delegate parameter inside of creating a function anywhere else and passing the function name. The anonymous function uses the delegate keyword while delegate initialization writes a block of code. You can also pass a parameter for an anonymous function as follows:

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

namespace Anonymous
{
    class Class1    {
        public delegate void Delstring Mesg);

        static void Main(string[] args)
        {
            Del obj = delegate(string Mesg) {
                Console.WriteLine(Mesg);
            };

            obj("Class1.fun");
        }
    }
}
Note:
You cannot use goto, break and continue statements inside the anonymous method block if the targat is outside an anonymous block.
Difference between Delegate and Event


0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives