Essential C# Events  Suggest an edit

Creating custom EventArgs containing additional data

Custom events usually need custom event arguments containing information about the event. For example MouseEventArgs which is used by mouse events like MouseDown or MouseUp events, contains information about Location or Buttons which used to generate the event.

When creating new events, to create a custom event arg:

Example

In the below example, we create a PriceChangingEventArgs event for Price property of a class. The event data class contains a CurrentPrice and a NewPrice. The event raises when you assign a new value to Price property and lets the consumer know the value is changing and let them to know about current price and new price:

PriceChangingEventArgs

public class PriceChangingEventArgs : EventArgs
{
    public PriceChangingEventArgs(int currentPrice, int newPrice)
    {
        this.CurrentPrice = currentPrice;
        this.NewPrice = newPrice;
    }

    public int CurrentPrice { get; private set; }
    public int NewPrice { get; private set; }
}

Product

public class Product
{
    public event EventHandler<PriceChangingEventArgs> PriceChanging;

    int price;
    public int Price
    {
        get { return price; }
        set
        {
            var e = new PriceChangingEventArgs(price, value);
            OnPriceChanging(e);
            price = value;
        }
    }

    protected void OnPriceChanging(PriceChangingEventArgs e)
    {
        var handler = PriceChanging;
        if (handler != null)
            handler(this, e);
    }
}

You can enhance the example by allowing the consumer to change the new value and then the value will be used for property. To do so it’s enough to apply these changes in classes.

Change the definition of NewPrice to be settable:

public int NewPrice { get; set; }

Change the definition of Price to use e.NewPrice as value of property, after calling OnPriceChanging :

int price;
public int Price
{
    get { return price; }
    set
    {
        var e = new PriceChangingEventArgs(price, value);
        OnPriceChanging(e);
        price = e.NewPrice;
    }
}


Table Of Contents
22 Enum
25 GUID
89 Events
107 Stream
108 Timers
  ↑ ↓ to navigate     ↵ to select     Esc to close