Tuesday, May 1, 2007

Event Handling example

I was trying to learn about the event handling mechanism in .net and stumbled across lot of good examples. Here is a version, I wrote using those examples (Credit goes to the original author who wrote this one). Apologize for the poor indentation :(

SourceURL: http://www.codeguru.com/csharp/csharp/cs_delegates/eventhandling/article.php/c4769/

namespace TestConsole
{
//Declare a delegate for EventHandlers
public delegate void MyEventHanlder(object sender, MyEventArgs e);

//Declare custom EventArgs to pass the event data
public class MyEventArgs : EventArgs
{
//field to capture the event data
public string MyEventArgumentData;
}

//class responsible for raising the event
class Publisher
{
//Declare the Event whose type is of delegate type
public event MyEventHanlder MyEvent;

//Function that raises the event
public void OnMyEvent(MyEventArgs e)
{
//Check for any subscribers
if (MyEvent != null)
{
//Sending a notification to all the subscribers of the event
MyEvent(this, e);
}
}
}


//class reponsible for handling the event
class Subscriber1
{
//Implement the EventHandler
public void OnMyEventHandler1(object sender, MyEventArgs e)
{
Console.WriteLine("In the subscriber 1 event handler and the EventArgs is {0}", e.MyEventArgumentData);
}

//Subscribe to the Event

public Subscriber1(Publisher p)
{
p.MyEvent += new MyEventHanlder(OnMyEventHandler1);
}
}

//class responsible for handling the event
class Subscriber2
{
//Implement the EventHandler
public void OnMyEventHandler2(object sender, MyEventArgs e)
{
Console.WriteLine("In the subscriber 2 event handler and the EventArgs is {0}", e.MyEventArgumentData);
}

//Subscribe to the Event
public Subscriber2(Publisher p)
{
p.MyEvent += new MyEventHanlder(OnMyEventHandler2);
}
}
}

Invoking Class:

class Program
{
static void Main(string[] args)
{
Publisher p = new Publisher();
Subscriber1 s1 = new Subscriber1(p);
Subscriber2 s2 = new Subscriber2(p);
MyEventArgs e1 = new MyEventArgs();
e1.MyEventArgumentData = "Event 1";
p.OnMyEvent(e1);
}
}

1 comment:

Anonymous said...

Se vi inieressano i cavalli consultate www.imieicavalli.blogspot.com
If you are intetrested about horses visit www.imieicavalli.blogspot.com

Post a Comment