Is there a better way to write this repetitive event-declaration code in C# when implementing an int

Posted by Damien Wildfire on Stack Overflow See other posts from Stack Overflow or by Damien Wildfire
Published on 2010-05-06T18:20:19Z Indexed on 2010/05/06 18:38 UTC
Read the original article Hit count: 177

Filed under:
|
|
|

I have a lot of code like the following, where I explicitly implement some events required by an interface.

public class IMicrowaveNotifier {
  event EventHandler<EventArgs> DoorClosed;
  event EventHandler<EventArgs> LightbulbOn;
  // ...
}

public class Microwave : IMicrowaveNotifier {
  private EventHandler<EventArgs> _doorClosed;
  event EventHandler<EventArgs> IMicrowaveNotifier.DoorClosed {
    add { lock (this) _doorClosed += value; }
    remove { lock (this) _doorClosed -= value; }
  }

  private EventHandler<EventArgs> _lightbulbOn;
  event EventHandler<EventArgs> IMicrowaveNotifier.LightbulbOn {
    add { lock (this) _lightbulbOn += value; }
    remove { lock (this) _lightbulbOn -= value; }
  }

  // ...
}

You can see that much of this is boilerplate. In Ruby I'd be able to do something like this:

class Microwave
  has_events :door_closed, :lightbulb_on, ...
end

Is there a similar shorter way of removing this boilerplate in C#?


Update: I left a very important part out of my example: namely, the events getting implemented are part of an interface, and I want to implement it explicitly. Sorry for not mentioning this earlier!

© Stack Overflow or respective owner

Related posts about c#

Related posts about event