0

I'm trying to forward events from one class to objects contained within it (as described here: Forwarding events in C#). However, the events are of different type.

For example, I have a class Item which exposes a ValueChanged event handler of type EventHandler. The class ItemHaver exposes an EventHandler<StatusEventArgs>, which should fire whenever Item.ValueChanged does, but should also provide additional information. How do I properly implement add/remove to the ItemValueChanged event declaration?

In the below code, would the lambda function in the add method perform the correct action, and if so, what's the proper way to handle the remove?

class Item
{
    public event EventHandler ValueChanged;
}

class ItemHaver
{
    private int _status;
    private Item _item;

    public event EventHandler<StatusEventArgs> ItemValueChanged
    {
        add 
        { 
            _item.ValueChanged += value; // Wrong type
            _item.ValueChanged += 
                (obj, e) => value(obj, new StatusEventArgs(this._status));
        }
        remove 
        { 
            _item.ValueChanged -= // Does this even work?
                (obj, e) => value(obj, new StatusEventArgs(this._status));  
        }
    }
}

class StatusEventArgs : EventArgs
{
    int Status { get; private set; }
    StatusEventArgs(int status) { Status = status; }
}
Community
  • 1
  • 1
Harrison Paine
  • 611
  • 5
  • 14

1 Answers1

2

I'd try using a dictionary in which I map the handlers.

class ItemHaver
{
    private int _status;
    private Item _item;

    private Dictionary<EventHandler<StatusEventArgs>, EventHandler> handlersMap = new Dictionary<EventHandler<StatusEventArgs>, EventHandler>();

    public event EventHandler<StatusEventArgs> ItemValueChanged
    {
        add
        {
            // _item.ValueChanged += value; // Wrong type
            handlersMap.Add(value, (obj, e) => value(obj, new StatusEventArgs(this._status)));
            _item.ValueChanged += handlersMap[value];
        }
        remove
        {
            _item.ValueChanged -= handlersMap[value];
        }
    }
}
Bartosz Wójtowicz
  • 1,321
  • 10
  • 18
  • Thanks, this seems to work. I actually performed a deeper refactoring and changed the underlying EventHandler on the `Item` class to match what was expected (the actual code involved many different types of `Item`, all developed in C# prior to generics. In any case, I can't comment on the efficiency of your method, but it did work as a temporary fix. – Harrison Paine Jun 24 '14 at 13:54