Learning Events And Delegates - Part 2

delegate

Walk-through

  • 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.
We have learned the basics of delegates in my previous article. This is part 2 in continuation with my previous article if you want some basic knowledge about the delegates you can prefer to read my previous blog first:

Now, we will talk about the delegates to some more depth and explore their types.

Types of Delegates

There are two types of delegates:

  • Single Cast Delegates
  • Multi Cast Delegates

So far I taught single cast delegates in which we invoked only one method using the delegates, Multi Cast Delegates are the delegates in which we have assigned address of more than one method. The thing that is important is that the methods called by the delegate will be called in the sequence they have assigned, the return type of the multicast delegate should be void type and all the methods assigned to the delegate should have the same signature as the signature of the delegate.

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

Note: To assign a method to the delegate use += and to remove method reference from delegate use -=.

Uses of Delegates

 

  • Abstract and encapsulate a method
  • For Callback mechanism
  • Asynchronous processing
  • Multicasting - Sequential processing

Here's the output of the program:

Output

Thanks Folks!