Adam Turner wrote: Is there a way to fire an event in a class, from outside that class? No, events can only be fired by the class that defines them. However, if you follow the recommended event pattern* then classes that inherit from ClassB could fire the event. *The recommended patter is to define your event, MyEvent then also have a protected method called OnMyEvent(MyEventArgs e). In the class defining the event, OnMyEvent just fires the event. If a class inherits from the one defining the event then there are three purposes for the OnMyEvent method. First is to handle the MyEvent event, without needlessly attaching a delegate to the event. The second purpose ties in with the first, by not calling base.OnMyEvent(e); in your derived class you can prevent the event from firing. This is useful if you wish to restrict the times when the event is fired. The third purpose can be to fire the event from within the derived class, this one is trickier because ensure that you don't break any implied behavior concerned with the event firing. To fire it, just call OnMyEvent and pass in the appropriate EventArgs object. Of course, an example :)
class TheBase
{
public event EventHandler MyEvent;
protected virtual void OnMyEvent(EventArgs e)
{
if( MyEvent != null )
{
MyEvent(this, e);
}
}
}
class TheDerived
{
protected override void OnMyEvent(EventArgs e)
{
if( ShouldFireMyEvent )
{
base.OnMyEvent(e);
}
else
{
// the MyEvent event will not be fired
}
}
public void FireMyEvent()
{
// CAUTION: Fire MyEvent only if the code using this event is guaranteed
// not to break because the Event was fired outside of its normal usage.
//
// IOW, if several events fire in a sequence, you must fire all of them
// in that sequence. Also don't fire this event yourself if you have
// other means of doing so (such as calling Invalidate in a Windows
// Forms Control instead of firing the Paint event yourself.)
OnMyEvent(EventArgs.Empty);
}
}
HTH, James "It is self repeating, of unknown pattern" Data - Star Trek: The Next Generation