views:

54

answers:

2

I ran across this pattern in the code of a library I'm using. It sets state within the event raising method, but only if the event is not null.

protected virtual void OnMyEvent(EventArgs e)
{
  if(MyEvent != null)
  {
     EnsureChildControls(); 
     MyEvent(this,e);
  }
}

Which means that the state is not set when overriding the method:

protected override void OnMyEvent(EventArgs e)
{
   base.OnMyEvent(e);
   Debug.Assert( /* Child controls ensured */); // This fails
}

but is only set when handling the event:

foo.MyEvent += (o, args) => Debug.Assert(/* Child controls ensured */); // This passes

Setting state within the if(MyEvent != null) seems like bad form, but I've checked the Event Design Guidelines and it doesn't mention this.

Do you think this code is incorrect? If so, why? (Reference to design guidelines would be helpful).

Edit for Context:

It's a Control, I'm trying to create subclass of it, and the state that it's setting is calling EnsureChildControls() conditionally based upon there being an event handler. I can call EnsureChildControls() myself, but I consider that something of a hack.

+3  A: 

I doubt you'll find any guidelines on something like this. Guidelines are typically for extremely common occurrences (which I wouldn't consider this).

Regarding the practice itself: I don't see any problem with doing it this way.

For what it's worth, you can avoid if(MyEvent != null) if you use this:

// initialize with empty delegate so MyEvent will never == null
public event MyEventHandler MyEvent = delegate {};
Dinah
Keen - that initialization is a nifty little tip to keep in the back of my head.
48klocs
A: 

This answer provides an MSDN quote that answers my question:

http://stackoverflow.com/questions/159317/when-should-you-override-onevent-as-opposed-to-subscribing-to-the-event-when-inhe/159334#159334

The protected OnEventName method also allows derived classes to override the event without attaching a delegate to it. A derived class must always call the OnEventName method of the base class to ensure that registered delegates receive the event.

Greg