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.
- using System;
-
- namespace Sumit_Delegate_Sample
- {
- class Program
- {
-
- public delegate int DoAll(int a, int b);
-
- static void Main(string[] args)
- {
-
- DoAll doit = add;
-
-
- Console.WriteLine("Output is: "+ doit(2,3));
- Console.ReadKey();
- }
-
-
-
-
- public static int add(int x, int y)
- {
- return x+y;
- }
-
- }
- }
Above example is an example for Single-cast Delegate in which only one method is assigned to the delegate.
The Output of program is:
Thanks Folks!