Skip to content

Instantly share code, notes, and snippets.

@davidalencar
Created August 15, 2012 07:38
Show Gist options
  • Save davidalencar/3357408 to your computer and use it in GitHub Desktop.
Save davidalencar/3357408 to your computer and use it in GitHub Desktop.
Event in C#
using System;
namespace test
{
class Program
{
static void Main(string[] args)
{
new TestStock().testStock();
Console.ReadKey();
}
}
class PriceChangedEventArgs : EventArgs
{
public readonly decimal LastPrice;
public readonly decimal NewPrice;
public PriceChangedEventArgs(decimal lastPrice, decimal newPrice)
{
LastPrice = lastPrice;
NewPrice = newPrice;
}
public override string ToString()
{
return string.Format("Price is changed: Last {0}, New {1}", this.LastPrice, this.NewPrice);
}
}
class Stock
{
decimal price;
public decimal Price
{
get
{
return price;
}
set
{
if (price == value) return;
decimal oldPrice = price;
price = value;
OnPriceChanged(new PriceChangedEventArgs(oldPrice, price));
}
}
public event EventHandler<PriceChangedEventArgs> PriceChanged;
protected virtual void OnPriceChanged(PriceChangedEventArgs e)
{
var temp = PriceChanged;
if (temp != null)
{
temp(this, e);
}
}
}
class TestStock
{
public void testStock()
{
var stock = new Stock();
stock.PriceChanged += stock_PriceChanged;
stock.Price = 10;
}
void stock_PriceChanged(object sender, PriceChangedEventArgs e)
{
Console.WriteLine(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment