Search This Blog

Wednesday, October 23, 2013

Events in C#

An event is a message sent by an object to signal the occurrence of an action.
An event in C# is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object.
The most use for events is in graphical user interfaces and the action could be caused by user interaction or it could be triggered by some other program logic.

Example:

// Declare a delegate for an event. 
delegate void EventHandler();

class Product
{
public string Name { get; set; }
       private int mQuantity;
       public int Quantity
       {
            get
            {
                  return mQuantity;
             }
             set
             {
                    mQuantity = value;
                    OnQuantityChange();
              }
       }

      // Declare event. 
       public event EventHandler QuantityChangeEvent;

       // This is called to fire the event.
       public void OnQuantityChange()
       {
              if (QuantityChangeEvent != null)
                     QuantityChangeEvent();
             }
}

 
static void handler()
{
      MessageBox.Show("Quantity changed!"); 
}

Product p = new Product();

//Add handler() to the event list.
p.QuantityChangeEvent += new EventHandler(handler);
p.Name = "Prod A";
p.Quantity = 10;
p.Quantity = 0;

<< Anonymous functions