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; }
}
I'd try using a dictionary in which I map the handlers.