Learning Events And Delegates - Part 1

Walkthrough

  • Introduction to Delegates with basic example
  • Types of delegates and their uses with example
  • Introduction to Events in C#
  • Using Events and their use with example

Delegates is a word that horrifies new programmers but here I am trying to make it as simple as I can. After reading this article you will find that Delegates are easy to use and learn.

Delegates in C# is a great feature in the language, since we previously had pointers those were unsafe and are not typesafe but here in C# Delegates are both safe and typesafe both.

Delegates as a real meaning in English is “Entrust” a task or responsibility given to another person, typically one who is less senior than oneself, we can say that Delegates are the representative, for example, Indian delegates for US are the representative of India in US delegate works as a bridge between the two countries.

There are four steps to use a delegate in C#.

Step 1: Declare a Delegate.

Step 2: Define the handler Method.

Step 3: Instantiate the delegate.

Step 4: Use Delegate.

The following is an example program for Delegate.

  1. using System;  
  2.   
  3. namespace Sumit_Delegate_Sample  
  4. {  
  5.     class Program  
  6.     {  
  7.         // STEP 1: Declare a Delegate  
  8.         public delegate int DoAll(int a, int b);  
  9.           
  10.             static void Main(string[] args)  
  11.         {  
  12.                 // Create instance of delegate  
  13.                 DoAll doit = add;  
  14.   
  15.                 // Use Delegate like a method  
  16.                 Console.WriteLine("Output is: "+ doit(2,3));  
  17.                 Console.ReadKey();  
  18.         }  
  19.   
  20.   
  21.   
  22.         // STEP 2: Define handeler Method (Declare a method with the same signature as the delegate.)  
  23.         public static int add(int x, int y)  
  24.         {  
  25.             return x+y;  
  26.         }  
  27.   
  28.     }  
  29. }  
Above example is an example for Single-cast Delegate in which only one method is assigned to the delegate.

The Output of program is:

Output

Thanks Folks!