Is it OK to set state within Event Raising methods?
- by Greg
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)
{
State = "Executing"; // Only sets state if MyEvent != null.
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( State == "Executing" ); // This fails
}
but is only set when handling the event:
foo.MyEvent += (o, args) => Debug.Assert(State == "Executing"); // 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.