Having trouble with an event in a derived class

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a class that generates an event and I have a derived class thereof
that needs to generate the same event. I tried making the event virtual but
that didn't accomplish what I want, although logically I think it should.

The best I've been able to do is have two events and then have the app
register the handler with both, but that seems to be poor style.

I've also tried to have the accessor-declarations for the event in the
derived class handle both registrations, but to no avail.

(I'm using C# with VS.net 2003)
 
PIEBALD said:
I have a class that generates an event and I have a derived class thereof
that needs to generate the same event. I tried making the event virtual
but
that didn't accomplish what I want, although logically I think it should.

The best I've been able to do is have two events and then have the app
register the handler with both, but that seems to be poor style.

The standard way to do this is have the base class declare the event
(non-virtual!), and a method with the following layout:
protected OnEventName(EventArgs e) {
if(EventName != null) {
EventName(this, e);
}
}

then your child class just needs to call OnEventName.
 
Here's an example that works:

using System;

namespace ConsoleApplication2
{
public class NothingMuch
{
[STAThread]
static void Main(string[] args)
{
Class2 test = new Class2();
test.StatusChanged += new EventHandler(test_StatusChanged);
test.Class1_GenerateEvent();
test.Class2_GenerateEvent();
}
private static void test_StatusChanged(object sender, EventArgs e)
{
Console.WriteLine( "Event Handled" );
}
}

public class Class1
{
public event EventHandler StatusChanged;
protected void OnStatusChanged( EventArgs args )
{
if ( StatusChanged != null )
StatusChanged( this, args );
}
public void Class1_GenerateEvent()
{
OnStatusChanged( new EventArgs() );
}
}

public class Class2 : Class1
{
public void Class2_GenerateEvent()
{
OnStatusChanged( new EventArgs() );
}
}
}
 
Back
Top