The blog has moved to the new site

Monday, June 13, 2016

Delegates in C# with examples

Delegate is type safe function pointer.

Function pointer: points/holds referernce to a method.

Type safe:  return type and signature of method must be same as signature and return type of method else you will get compilation error.

Syntax:  Very much similar to the method with the delegate keyword.

It is similar to a class, we need to create instance of it and pass in the function name to the delegate constructor and this is the function the delegate will point to.

It calls the method indirectly via a pointer.

It is representative to communicate between two parties.

When you want to pass function as parameter to another funtion than think of delegates.

Main use of delegates in c# is Callbacks & communication between two parties.


Example1:  Suppose we have report class and in that we have download report method. At real time you want to know the percentage of report downloaded, so in that case we can make use of delegates as below,

class Program
        static void Main(string[] args)
       // holds reference to function.

        // callback function which you want to call using delegates.
        static void ReportDownloadStatus(int i)

    public class Report
        //declare delegate
        public delegate void PercentageCompleted(int i);
        // delegate passed as a function parameter
        public static void DownloadReport(PercentageCompleted percentageCompleted) 
            // Gathering and printing data
            for (int i = 0; i <= 100; i++)

            Console.WriteLine("Report Downloaded completly.");

Example2: Calling content page method from master page method / Click events.


             protected void Button1_Click(object sender, EventArgs e)
                 if (contentCallEvent != null)
                   contentCallEvent(this, EventArgs.Empty);

            public event EventHandler contentCallEvent;


protected void Page_PreInit(object sender, EventArgs e)
               // Create an event handler for the master page's contentCallEvent event
               Master.contentCallEvent += new EventHandler(PrintData);

           private void PrintData(object sender, EventArgs e)
              // This Method will be Called.
              lbl.Text = "Delegates";


<%@ MasterType VirtualPath="~/Site.Master" %>

Dear Reader, please give suggestion on it, or let me know if you have good examples for delegates.

1 comment:

  1. its better provide some more information,
    any way nice work

    Dotnet Begineers