Delegate in C# with Example

Delegate in C# with Example
Delegate in C# with Example

A delegate is a reference type.  To create a delegate, we make use of a delegate keyword. The syntax of a delegate is pretty much similar to the syntax of a method, but with a delegate keyword.  A delegate always holds reference to a method and whenever you invoke the delegate, that method will be invoked.  We have seen how to pass different type of parameters like string, int, float, double, etc but a delegate helps you to pass a method as a parameter and you can invoke it at any point in time.

Creating an instance of delegate is similar to creating an instance of a class, but you must pass a method name to it.  The return type and signature of the method should match the return type and signature of the delegate, that is why a delegate is also called type safe function pointer.

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

namespace Hello
{   
    //Delegate declaration
    public delegate void mydelegate(string name);
   

    class Program
    {
        static void Main(string[] args)
        {
            mydelegate _myname = new mydelegate(PrintName);

            _myname("Peter Parker");
        }

        //Method to pass
        public static void PrintName(string name)
        {
            Console.WriteLine("My name is {0}.", name);
        }
            
    }
}

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •