Standard Event Pattern - CSharp Custom Type

CSharp examples for Custom Type:Event

Introduction

At the core of the standard event pattern is System.EventArgs, a predefined Framework class.

EventArgs is a base class for conveying information for an event.

Demo Code

using System;//w w w. ja  va  2s. c  o m
public class PriceChangedEventArgs : EventArgs
{
   public readonly decimal LastPrice;
   public readonly decimal NewPrice;
   public PriceChangedEventArgs (decimal lastPrice, decimal newPrice)
   {
      LastPrice = lastPrice; NewPrice = newPrice;
   }
}
public class Product
{
   string symbol;
   decimal price;
   public Product (string symbol) {this.symbol = symbol;}
   public event EventHandler<PriceChangedEventArgs> PriceChanged;
   protected virtual void OnPriceChanged (PriceChangedEventArgs e)
   {
      PriceChanged?.Invoke (this, e);
   }
   public decimal Price
   {
      get { return price; }
      set
      {
         if (price == value) return;
         decimal oldPrice = price;
         price = value;
         OnPriceChanged (new PriceChangedEventArgs (oldPrice, price));
      }
   }
}
class Test
{
   static void Main()
   {
      Product p = new Product ("AAAA");
      p.Price = 27.10M;
      // Register with the PriceChanged event
      p.PriceChanged += product_PriceChanged;
      p.Price = 31.59M;
   }
   static void product_PriceChanged (object sender, PriceChangedEventArgs e)
   {
      if ((e.NewPrice - e.LastPrice) / e.LastPrice > 0.1M)
         Console.WriteLine ("Alert, 10% stock price increase!");
      }
}

Result


Related Tutorials