Thursday, 27 July 2017

What is delegate in C# and why we use it .

A delegate is like a pointer to a function. A delegate in C# is similar to a function pointer in C or C++. delegate keyword  used for make any function delegate. It is a reference type data type and it holds the reference of a method. We use System.Delegate namespace.. 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.It is also called delegate is  safe function pointer.


Example:

Syntax:
<access modifier> delegate <return type> <delegate_name>(<parameters>)

public delegate void delegate_name(<parameters>).


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace arraylist
{

    class Program
    {

        public delegate void Print(int value);  // Delegate and method or function have same syntax

        static void Main(string[] args)
        {
            // Print delegate points to PrintNumber
            Print printDel = PrintNumber;

            printDel(5);
            printDel(20);

            // Print delegate points to PrintMoney
            printDel = PrintMoney;

            printDel(52);
            printDel(75);
            Console.Read();
        }

        public static void PrintNumber(int num)  // Delegate and method or function have same syntax
        {
            Console.WriteLine("Numbers value are: {0}", num);
        }

        public static void PrintMoney(int money) // Delegate and method or function have same syntax
        {
            Console.WriteLine("Money sequence are: {0}", money);
        }
    }
}

Output:




Multicast delegate:

The delegate can points to more than one  methods in a program called Multicast delegate. The "+" operator adds a function to the delegate object and the "-" operator removes an existing function from a delegate object in the given program.

Example:



Share this


0 Comments

Advertisement