Jens Willmer

Tutorials, projects, dissertations and more..

How to use Eventhandlers in C#

class Program
{
	static void Main()
    {
		//init stock
        Stock s1 = new Stock();

		//add handler
        s1.PriceChanged += new PriceChangedHandler(s1_PriceChanged);
		s1.MyFunction += new MyFunctionhandler(s1_MyFunction);

		//change something
        s1.Price = 12;
        s1.myFunction(2);

        Console.Read();
    }

    public static void s1_PriceChanged(decimal a, decimal b)
    {
        Console.WriteLine("Old value: " + a + " - new value: " + b);
    }

    public static void s1_MyFunction(string s, int i)
    {
        Console.WriteLine(s + " - number:" + i.ToString());
    }
}

public delegate void PriceChangedHandler (decimal oldPrice, decimal newPrice);
public delegate void MyFunctionhandler (string hand, int p);

class Stock
{
    decimal price;

	//eventhandlers
    public event PriceChangedHandler PriceChanged;
    public event MyFunctionhandler MyFunction;

    public decimal Price
    {
        get { return price; }
        set {
            if (price == value) return;
			//if handler was added trow the event
            if (PriceChanged != null)
                PriceChanged(price, value);
            price = value;
        }
    }

    public void myFunction(int i)
    {
        if (i == 2 && MyFunction != null)
            MyFunction("left", 3);
    }
}