Anybody can explain Delegate and Event concept in C#?

Delegates in C# is function pointers in C++
It means you can create a reference to encapsulates a method (in VS 2003) and anonymous methods too (in VS 2005)

Events: Methods fired when something specifically done

Delegates in C# .Net:

If we look at C++ there is a feature called callback function. This feature uses Pointers to Functions to pass them as parameters to other functions. Delegate is a similar feature but it is more type safe, which stands as a stark contrast with C++ function pointers. A delegate can hold reference/s to one more more functions and invoke them as and when needed.

A delegate needs the method's name and its parameters (input and output variables) when we create a delegate. But delegate is not a standalone construction. It is a class. Any delegate is inherited from base delegate class of .NET class library when it is declared. This can be from either of the two classes from System.Delegate or System.MulticastDelegate.
If the delegate contains a return type of [I]void[/I], then it is automatically aliased to the type of System.MulticastDelegate. This can support multiple functions with a += operator. If the delegate contains a non-void return type then it is aliased to System.Delegate class and it cannot support multiple methods.
Let us have a look at the following sample code.

class Figure
{ 
    public Figure(float a, float b, float c) 
   { 
       m_xPos = a;
       m_yPos = b;
       m_zPos = c;
    }     public void InvertX()
    {
        m_xPos = - m_xPos; 
    } 
   public void InvertY()
  {
     m_yPos = - m_yPos;
   } 
   public void InvertZ()
  {
     m_zPos = - m_zPos;
   }
   private float m_xPos = 0;
   private float m_yPos = 0;
   private float m_zPos = 0;
}

Now, we have a class named Figure and it has three private fields that use to store position and three methods to invert this position by every axis. In main class we declare delegate as follows:

public delegate void FigureDelegate();

And now in the main function we should use it like this:

Figure figure = new Figure(10,20,30);
FigureDelegate fx = new FigureDelegate(figure.InvertX); 
FigureDelegate fy = new FigureDelegate(figure.InvertY); 
FigureDelegate fz = new FigureDelegate(figure.InvertZ); 
MulticastDelegate f_del = fx+fy+fz;

In this example we create three delegates of FigureDelegate type and attach to these elements our three methods from Figure class. Now every delegate keeps the address of the attached function. The last line of code is very interesting, here we create a delegate of base type (MulticastDelegate) and attach three of our already created delegates. As all our methods are of void return type they are automatically of type MutlticastDelegate and a MulticastDelegate can support multiple methods invocation also. Hence we can write

Figure figure = new Figure(10,20,30); 
FigureDelegate fMulti = new FigureDelegate(figure.InvertX); 
fMulti += new FigureDelegate(figure.InvertY); 
fMulti();

Events in C# .Net:

Delegate usefulness does not just lie in the fact that it can hold the references to functions but in the fact that it can define and use function names at runtime and not at compile time. A large goal of design delegates is their applicability in events model of .Net. Events are the actions of the system on user manipulations (e.g. mouse clicks, key press, timer etc.) or any event triggered by the program. To understand the usage of delegates for event model, the previous examples are used here. We should add to our Figure class next things:

public delegate void FigureHandler(string msg); 
public static event FigureHandler Inverted;  public void InvertZ() 
{
   m_zPos = - m_zPos; 
   Inverted("inverted by z-axis"); 
}

Now we have a delegate declared and event that uses this delegate's type. In every function we should call our event. The next code snippet should explain it clearly:

static void Main(string[] args) 
{     Figure figure = new Figure(10,20,30);
   Figure.Inverted+=new Test.Figure.FigureHandler(OnFigureInverted); 
   figure.InvertX(); 
   figure.InvertZ(); 
} 
private static void OnFigureInverted(string msg) 
{ 
  Console.WriteLine("Figure was {0}",msg); 
} 

So, in the main function we should create an object of figure class and attach event handler to the method [I]OnFigureInverted[/I]. And when we call any of invert methods the event is fired and it calls our event handler. The application will print the following string into the console: "Figure was inverted by x-axis Figure was inverted by z-axis". These are simple examples of using delegates and events and should a starting point to learn more.

Edited 3 Years Ago by pyTony: fixed formatting

This article has been dead for over six months. Start a new discussion instead.