Delegates Delegates are type safe reference/pointers & ability to point to any methods. By using a delegate, a program can dynamically call different methods at runtime
Events An event is a user defined runtime entity, used to achieve the dynamic communication by means of program elements rather than procedural flow of control from one part to another. It is the way to establish the connection between program occurrence and resulting actions at runtime.
Consider the following example in which an event will be thrown whenever an element is inserted into the list.
using System; using System.Collections.Generic; using System.Text; using System.Collections;
namespace DelegateEventDemo { public delegate void AddEvent(object sender,EventArgs e);
class DelegateHandler { public event AddEvent OnAdditionToList; public ArrayList al = new ArrayList();
public DelegateHandler() { // Registering the Changed method to event OnAdditionToList += new AddEvent(Changed); }
public void OnListChanged(EventArgs e) { // Publish the event : Listening if (OnAdditionToList != null) OnAdditionToList(this, e); }
private void Changed(object sender,EventArgs e) { // Notify the user Console.WriteLine("New element has been inserted into the list."); }
public ArrayList Add(int num) { al.Add(num); // Fier the event it on occure OnListChanged(EventArgs.Empty); return al; }
public ArrayList Get() { return al; }
}
class Program { static void Main(string[] args) { DelegateHandler dh = new DelegateHandler();
// Client side handling of event dh.OnAdditionToList += new AddEvent(ClientFunction);
for (int i = 1; i <= 10; i++) dh.Add(i * 10);
ArrayList al = dh.Get();
for (int i = 0; i < al.Count; i++) Console.WriteLine(al[i].ToString());
Console.ReadLine(); }
public static void ClientFunction(object sender, EventArgs e) { Console.WriteLine("Client handler is called.");
}
} }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|