C# Delegates

A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. 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

so A function can have one or more parameters of different data types, but what if you want to pass a function itself as a parameter? How does C# handle the callback functions or event handler? The answer is - delegate.


A delegate can be declared using delegate keyword followed by a function signature as shown below.

Syntax:

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

Syntax Example:

public delegate void Print(int value);





Example :


using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Text;

using System.Threading.Tasks;



namespace ConsoleApplication1

{



  // Declaration

  public delegate void SimpleDelegate();



  class TestDelegate

  {

    public static void MyFunc()

    {

      Console.WriteLine("Hi , Nitin kumar, I am MyFunc() function and i was called by delegate ...");

    }



    public static void Main()

    {

      // Instantiation

      SimpleDelegate simpleDelegate = new SimpleDelegate(MyFunc);



      // Invocation

      simpleDelegate();

      Console.Read();

    }

  }

}





 OutPut :