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)
{
Shipment myItem = new Shipment();
myItem.OnShipmentMade +=
new Shipment.ShipmentHandler(ShowUserMessage);
myItem.TrackingNumber = "1ZY444567";
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;
}
public string Message
{
get
{
return message;
}
}
}
}
Finally, here it is the object:
using System;
namespace EventExample
{
public class Shipment
{
private string trackingnumber;
public delegate void ShipmentHandler(object myObject,
ShipArgs myArgs);
public event ShipmentHandler OnShipmentMade;
public string TrackingNumber
{
set
{
trackingnumber = value;
if (trackingnumber.Length != 0)
{
ShipArgs myArgs = new ShipArgs("Item has been shipped.");
OnShipmentMade(this, myArgs);
}
}
}
public Shipment()
{
}
}
}