tags:

views:

59

answers:

3

My base interface IFoo declares

event EventHandler OnChanged

when I do 'implement interface' I get some lame boilerplate code but how do I provide a decent default implementation?

add { throw new NotImplementedException(); }
remove { throw new NotImplementedException(); }
+1  A: 
private EventHandler onChanged;

event EventHandler IFoo.OnChanged
{
    add
    {
        onChanged += value;
    }
    remove
    {
        onChanged -= value;
    }
}
Tim Lovell-Smith
+4  A: 

How does the interface declare the event with the interface name prefixed on the event name? I'm not sure that's legal C#.

If you can get away without the "IFoo." prefix, just declare the event in your class and let the compiler create the default add/remove handers for you. All you should have to worry about is when to trigger the event:

interface IFoo
{
    event EventHandler OnChanged;
}

class MyClass : IFoo
{
    public event EventHandler OnChanged;

    private FireOnChanged()
    {
        EventHandler handler = this.OnChanged;
        if (handler != null)
        {
            handler(this, EventArgs.Empty); // with appropriate args, of course...
        }
    }
}

... Or did I misunderstand about where you're inheriting the event from? is your class derived from an abstract base class which in turn implements an interface (which declares the event)? That could be what you mean, but it wasn't clear in the question.

JaredReisinger
You're right, the interface doesn't declare it with interface name prefixed, we just declare it that way when we declare the implementation. Will update OP.
Tim Lovell-Smith
A: 

I recommend you change the name of the event to conform with common naming standards of events. In this case Changed. Link to previous post

   private System.EventHandler _Changed;

    private readonly object _EventLock = new object();

    public event System.EventHandler Changed {
        add {
            lock (_EventLock) {
                _Changed += value;
            }
        }
        remove {
            lock (_EventLock) {
                _Changed -= value;
            }
        }
    }

    protected virtual void OnChanged(System.EventArgs args) {

        System.EventHandler handler = _Changed;
        if (handler != null) {
            handler(this, args);
        }
    }
MaLio