Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0192 C# standard event pattern

C# has a standard event pattern. It defines a standard class to accept the parameters for various events. Event parameter should subclass System.EventArgs to create its own event data. public class ValueChangedEventArgs : System.EventArgs { public readonly string str; public ValueChangedEventArgs(string str) { this.str = str; } } C# provides a generic delegate for the event handler. public delegate void EventHandler<TEventArgs>(object source, TEventArgs e) where TEventArgs : EventArgs; We should follow the pattern when defining our own event handlers. using System; public class ValueChangedEventArgs : System.EventArgs { public readonly string str; public ValueChangedEventArgs(string str) { this.str = str; } } class Printer { public event EventHandler<ValueChangedEventArgs> ValuesChanged; private string stringValue; protected virtual void OnPriceChanged(ValueChangedEventArgs e) { if (ValuesChanged != null) ValuesChanged(this, e); } public string StringValue { get { return stringValue; } set { OnPriceChanged(new ValueChangedEventArgs(value)); stringValue = value; } } } class Test { static void stock_PriceChanged(object sender, ValueChangedEventArgs e) { Console.WriteLine("event!"); } static void Main() { Printer p = new Printer(); p.StringValue = "rntsoft.com"; } }