Creating custom EventArgs containing additional data

suggest change

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;
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents