Creating advanced C# custom events






3.42/5 (56 votes)
Jan 20, 2005

222652

2455
Hooking up C# objects with delegate events.
Introduction
Hooking Custom Events and its arguments to an Object.
In this article, I will try to illustrate how to hook a custom event to an object. We will go a little bit advanced and also create our own event arguments that are derived from the EventArgs
base class.
As you will see throughout the code, there is an item object which refers to an inventory item. Our object will raise an event when it has a valid shipment tracking number.
Let's take a look the main program that uses our item object:
using System;
namespace EventExample
{
class Class1
{
static void Main(string[] args)
{
// we will create our instance
Shipment myItem = new Shipment();
// we need to add the delegate event to new object
myItem.OnShipmentMade +=
new Shipment.ShipmentHandler(ShowUserMessage);
// we assumed that the item has been just shipped and
// we are assigning a tracking number to it.
myItem.TrackingNumber = "1ZY444567";
// The common procedure to see what is going on the
// console screen
Console.Read();
}
static void ShowUserMessage(object a, ShipArgs e)
{
Console.WriteLine(e.Message);
}
}
}
Now take a look into our custom event class:
using System;
namespace EventExample
{
public class ShipArgs : EventArgs
{
private string message;
public ShipArgs(string message)
{
this.message = message;
}
// This is a straightforward implementation for
// declaring a public field
public string Message
{
get
{
return message;
}
}
}
}
Finally, here it is the object:
using System;
namespace EventExample
{
public class Shipment
{
private string trackingnumber;
// The delegate procedure we are assigning to our object
public delegate void ShipmentHandler(object myObject,
ShipArgs myArgs);
public event ShipmentHandler OnShipmentMade;
public string TrackingNumber
{
set
{
trackingnumber = value;
// We need to check whether a tracking number
// was assigned to the field.
if (trackingnumber.Length != 0)
{
ShipArgs myArgs = new ShipArgs("Item has been shipped.");
// Tracking number is available, raise the event.
OnShipmentMade(this, myArgs);
}
}
}
public Shipment()
{
}
}
}