Showing posts with label events. Show all posts
Showing posts with label events. Show all posts

Wednesday, November 23, 2011

custom events at .net framework

The following procedure demonstrates how to add events that follow the standard .NET Framework pattern to your classes and structs.

//1. Define a class to hold custom event arguments
public class CustomEventArgs : EventArgs
{ // add the properties and attributes that needed to be passed in the event arguments
public CustomEventArgs(string s)
{
message = s;
}
private string message;

public string Message
{
get { return message; }
set { message = value; }
}
}

// 2. Class that publishes an event
class Publisher
{
// Declare the event using EventHandler
public event EventHandler MyCustomEvent;
}

//3. Class that subscribes to an event
class Subscriber
{
public Subscriber()
{
Publisher pub=new Publisher();
// Subscribe to the event using C# 2.0 syntax
pub.MyCustomEvent += new EventHandler(MyCustomEvent_Handler);
}

// Define what actions to take when the event is raised.
void MyCustomEvent_Handler(object sender, CustomEventArgs e)
{
// the event handler
--------> third line at execution
}
}

//4. class to raise the event

class Raiser
{
public void Mani()
{
Publisher pub=new Publisher(); -------> first line at execution
pub.MyCustomEvent(new CustomEventArgs("testing")); -----> second line at execution
}
}