Is there a better way to minimize this C# event repetition?

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:28 UTC
Read the original article Hit count: 191

Filed under:
|
|
|

I have a lot of code like this:

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

  private EventHandler<EventArgs> _lightbulbOn;
  public event EventHandler<EventArgs> 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#?

© Stack Overflow or respective owner

Related posts about c#

Related posts about event