using System;
namespace EventsExample {
// Create a delegate
public delegate void NameFoundEventHandler( object o, NameFoundEventArgs e );
// Define the Event Arguments (EventArgs) in an inherited class
public class NameFoundEventArgs : EventArgs {
public string Name;
public NameFoundEventArgs ( string name ) {
this.Name = name;
}
}
// Define a "program" class to simulate an event listener
public class Program {
// Create the event
public static event NameFoundEventHandler NameFound;
public static void Main () {
// Register a "to be initiated method" with the event
NameFound += new NameFoundEventHandler( sayHelloWorld );
// Create an array to store 10 first and surnames
string[] names = new string[10];
names[0] = "Tom Wadeson";
names[1] = "Andy Smith";
names[2] = "Ben Rogers";
names[3] = "Tom Saunders";
names[4] = "Billy Piper";
names[5] = "Sandy Leon";
names[6] = "Chris Stevenson";
names[7] = "Brad Friedal";
names[8] = "Tom Curtis";
names[9] = "Rich McGill";
Console.WriteLine( "Only people named \"Tom\" may speak:" );
// Iterate through the array, and initiate the NameFound event for all occurrences of "Tom"
foreach( string name in names ) {
if ( name.StartsWith( "Tom" ) ) {
NameFoundEventArgs e1 = new NameFoundEventArgs( name );
onNameFound( e1 );
}
}
Console.Read();
}
// Create the "onEvent" method
public static void onNameFound ( NameFoundEventArgs e ) {
if ( NameFound != null ) {
NameFound( new object(), e );
}
}
// Create the "initiated method" - the code to be executed upon occurrence of an event
public static void sayHelloWorld ( object o, NameFoundEventArgs e ) {
Console.WriteLine( "Hello, World! From {0}.", e.Name );
}
}
}