Thumb

What is delegate in C# and uses of delegates?

1/9/2020 12:00:00 AM

A delegate is a type safe function pointer. That is, it holds a reference (Pointer) to a function. The signature of the delegate must match the signature of the function, the delegate point 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. Given bellow the delegate example code:

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

namespace testFor
{
    //create a delegate
    public delegate void DelegatName(string name);
    class Program
    {
        static void Main(string[] args)
        {
            //create a object of the delegate and pass the method name as a parameter.
            //static method so can't create an object. 
            DelegatName deObj = new DelegatName(PrintName);
            deObj("Farhan Sakib Jesy");
            Console.Read();
        }
        public static void PrintName(string getName)
        {
            Console.WriteLine("My Name Is: "+getName);
        }
    }
}

Tip to remember delegate syntax: Delegates syntax look very much similar to a method with a delegate keyword.