Introduction to delegates:
Delegates are like the function pointers used in C++ or C.It holds the method/methods reference in an object. They are generally referred to as type safe function pointers.
Advantages:
- Delegates encapsulates the method's call from caller
- Use of delegate improves the performance of application
- Can be used to call a method asynchronously
- Delegates provide maximum flexibility at run time being type safe
Syntax:
public delegate typeofdelegate DelegateName(object obj1,object obj2)
e.g
public delegate void Compute(object obj1,object obj2);
Events and delegates work hand-in-hand to provide a program's functionality. It starts with a class that declares an event. Any class, including the same class that the event is declared in, may register/subscribe one of its methods for the event. This occurs through a delegate, which specifies the signature of the method that is registered for the event. The delegate may be one of the pre-defined .NET delegates or one you declare yourself. Whichever is appropriate, you assign the delegate to the event, which effectively registers the method that will be called when the event fires.
Subscribing/Registering to an Event:
- The += syntax registers a delegate with an event.
- To unregister with an event, use the -= with the same syntax.
STEPS :
- Declaring an event To declare an event inside a class, first a delegate type for the event must be declared, if none is already declared.
public delegate void Mydelegate(Object sender,EventArgs e);
Next, the event itself is declared.
public event EventHandler Added;
- Invoking an event Once a class has declared an event, it can treat that event just like a field of the indicated delegate type. The field will either be null, if no client has hooked up a delegate to the event, or else it refers to a delegate that should be called when the event is invoked. Thus, invoking an event is generally done by first checking for null and then calling the event.
if (Added != null)
Added(this,EventArgs.Empty); - Hooking up to an event From outside the class that declared it, an event looks like a field, but access to that field is very restricted. The only things that can be done are:
- Compose a new delegate onto that field.
- Remove a delegate from a (possibly composite) field.
pb.Added += sb.Handler;
/**
*
* @author ravikiran
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EventHandling
{
public delegate void Mydelegate(Object sender,EventArgs e);
class Publisher : EventArgs
{
public event EventHandler Added;
public void OnAdded()
{
if (Added != null)
Added(this,EventArgs.Empty);
}
}
class Subscriber
{
public void Handler(object sender, EventArgs e)
{
System.Console.WriteLine("Handler of subscriber being called");
}
}
class Program
{
static void Main(string[] args)
{
Publisher pb = new Publisher();
Subscriber sb = new Subscriber();
pb.Added += sb.Handler;
pb.OnAdded();
Console.ReadKey();
}
}
}