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!