Hi Action,
Don't do that. You'll get nothing but troubles.
class parent
{
public virtual event SomeDelegate SomeChanged;
}
class child : parent
{
void abc()
{
this.SomeChanged+=SomeMethod; // ok
if (this.SomeChanged != null) // can't
this.SomeChanged(); // can't
}
}
Remove the virtual keyword infront of the event declaration and this is the
way to go. The only thing you should do is to declare one protected virtual
OnXXX method that raises the event.
class parent
{
public event SomeDelegate SomeChanged;
protected virtual OnSomeChanged(SomeChangedEventArgs e)
{
if(SomeChanged != null)
SomeChanged(this, e);
}
}
That's it. If you want to raise the event from the child class simply call
OnSomeChanged method
If you want to handle the event in your derived class you have options:
either to hook the event or better to override OnSomeChanged method. If you
choose the latter you can suppress the event by not calling the base
implementation.
Don't ever use the following.
class parent
{
public virtual event SomeDelegate SomeChanged;
}
class child : parent
{
public override event SomeDelegate SomeChanged; // what's the use of
overriding a parent event?
}
void main()
{
parent childInstance = new childInstance;
childInstance.SomeChanged+=SomeMethod; // it's parent's one or child's
one?
}
When you declare an event using the syntax above you declare three things.
One private member of SomeDelegate type (this is what actually keeps the
chain of event handlers and what you test for null). Obviously it cannot be
virtual
And two public accessor methods *add* and *remove* which are actually
declared as virtual.
When you override that event you override the accessors and declare again
the member. So you end up having two different delagate members for the
parent and child classes. Because *add* and *remove* are virtual they always
update the child's memeber so the parent member is always null. If you don's
use virtual method for firing the event base class will never have that
event fired because from its perspective there are never be event handlers.
Actually events has one more accessor which is not supported by C# called
*invoke*. C++ porgrammers use to use it. Thus they use to use virtual
events. However it is always dangerous. So my suggestion is to stick with
OnXXX method and don't use virtual events.
--
HTH
Stoitcho Goutsev (100) [C# MVP]