I will explain what is delegate, why we use it and how many types of delegates with example.
What is Delegate
It is a type safe function pointer that holds the reference to function [Method]. Delegate is a type which represents the reference of a Method. The signature of the delegate must be same as method that is why we call the delegate as a type safe function pointer.
It is very similar to a class because we can also create instance of the delegate. When you create instance of delegate, you need to pass the method name as a parameter to delegate instance, so here delegate points to that method.

The following is the general syntax for delegate.
public delegate int MyDelegate(int x, int y);
Why Delegate
- You can call or invoke method through the Delegate instance.
- It is used to pass the Method as arguments to other method.
- It is used to define the callback methods.
- Events are used with delegate.

Example
- using System;
- namespace ConsoleDemo
- {
- public delegate void SampleDelegate(string msg);
- public class Program
- {
- public static void Show(string message)
- {
- Console.WriteLine(message);
- }
- public static void Main(string[] args)
- {
- SampleDelegate objSampleDelegate = new SampleDelegate(Show);
- objSampleDelegate("Welcome to sample delegate");
- Console.ReadLine();
- }
- }
- }

Multicast Delegate
It is a type of delegate which references more than one method. Call or Invoke the Multicast delegate invoking all methods which is referenced to it. It invokes the list of method in the same order in which they are added.

The following are the ways to attach or detach the method to the delegate.
- + or += to register a function or method with the delegate.
- – or -= to register a function or method with the delegate.
Note: A multicast delegate, invoke the methods in the invocation list, in the same order in which they are added.
If delegate return type is not void and it is multicast delegate then the value of last invoked method will return. Observer Design pattern is a simple example where we will see the use of multicast delegate. It is also called Publisher/Subscriber Pattern.
Example 1




Santhakumar MunuswamyPosted Oct 25, 2015, 11:29 AM
Good one
Nilesh JadavPosted Oct 23, 2015, 8:20 AM
Nice share !!
Dev ConceptPosted Oct 23, 2015, 4:41 AM
Good Share...
Sibeesh VenuPosted Oct 23, 2015, 1:35 AM
Nice Share
Priyaranjan K SPosted Oct 23, 2015, 12:10 AM
Good Share ..
Harshad PansuriyaPosted Oct 23, 2015, 12:02 AM
Nice one