Firing an event from outside the class
-
Is there a way to fire an event from a class, from outside that class? I mean, if i have something like the following, can ClassA fire ClassB's Click event?
public class ClassA
{
ClassB myB;
}
public class ClassB
{
public event EventHandler Click;
}I tried
myB.BeginInvoke(myB.Click, new object[] {null, null});
but it didnt compile Thanks Adam
-
Is there a way to fire an event from a class, from outside that class? I mean, if i have something like the following, can ClassA fire ClassB's Click event?
public class ClassA
{
ClassB myB;
}
public class ClassB
{
public event EventHandler Click;
}I tried
myB.BeginInvoke(myB.Click, new object[] {null, null});
but it didnt compile Thanks Adam
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 calledOnMyEvent(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 theOnMyEvent
method. First is to handle theMyEvent
event, without needlessly attaching a delegate to the event. The second purpose ties in with the first, by not callingbase.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 callOnMyEvent
and pass in the appropriateEventArgs
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