Kjara
Kjara

Reputation: 2912

cannot define EventHandler as event

I need an IDictionary<T,K> that raises an event whenever an item is added via the Add method. But the event that is raised should depend on the key of item, i.e. if I add ("hello","world") to such a dictionary, the "hello"-event should be raised, and if I add ("world","hello"), then the "world"-event should be raised.

So I tried to implement this and ended up with

class EventDictionary<T,K> : IDictionary<T,K>
{
    private IDictionary<T,K> _internalDic;
    private IDictionary<T, EventHandler> _onAddHandlers;

    public EventHandler OnAdd(T key)
    {
        if (!_onAddHandlers.ContainsKey(key))
            _onAddHandlers[key] = null;
        return _onAddHandlers[key];
    }

    public void Add(T key, K value)
    {
        _internalDic.Add(key, value);
        OnAdd(key)?.Invoke(this, EventArgs.Empty);
    }

    public void Add(KeyValuePair<T, K> item)
    {
        _internalDic.Add(item);
        OnAdd(item.Key)?.Invoke(this, EventArgs.Empty);
    }

    ... // implementing the other methods of IDictionary<T,K>
}

This compiles - as long as I don't add the event keyword:

private IDictionary<T, event EventHandler> _onAddHandlers; // syntax error

OR

public event EventHandler OnAdd(T key) { ... } // syntax error

Have I missed something? How can I make the OnAdd event handlers (all of them) events?

Upvotes: 0

Views: 57

Answers (1)

Servy
Servy

Reputation: 203821

There is no way to have a dynamic number of events on your type. Events, just like other members (fields, methods, properties) need to be statically defined at compile time. So you can have your dictionary of delegates, and you can add/remove delegates from the dictionary, and invoke those delegates when you want, but they won't be events on that class; they'll need to go through methods, as you've done so far.

If, instead, you just want to have a single event where the signature of the event is one where it accepts a parameter of type T, then you simply need to use an appropriate delegate, instead of EventHandler, when declaring your event:

public event Action<T> OnAdd; // syntax error

Upvotes: 1

Related Questions