1

I have two same events in different classes:

A.eventA

B.eventB

These two events: eventA and eventB are defined via the same delegate therefore the events have the same return value and parameters. Is it possible to fire A.eventA in the moment when B.eventB is fired?

I can write a method:

void return-value-of-delegate connect(parameters of delegate)
{
   if (A.eventA != null)
   {
      A.eventA(parameters of delegate);
   }
}

I was just wondering if I can shorten my code.

Thanks!

(Note: My code is a WPF project therefore WPF tag.)

EDIT: In class A is reference to the class B.

MartyIX
  • 27,828
  • 29
  • 136
  • 207

4 Answers4

1

You can not raise an event outside of the class. Only the class itself can raise it's own events. You can on the other hand, expose a public method accepting same parameters which internally raises the specified event.

Using Reflection is also not an option which only allows you to subscribe to and remove a subscription from an event of another class.

decyclone
  • 30,394
  • 6
  • 63
  • 80
1

Whenever EventB fires, EventA also fires:

class A {
  private B b;
  public event EventHandler EventA {
    add {
      b.EventB += value;
    }
    remove {
      b.EventB -= value;
    }
  }
  public A() {
    b = new B();
  }
  // ...
}

All the event listeners are registered in class B now.

Jordão
  • 55,340
  • 13
  • 112
  • 144
  • It seems it is what I was looking for. It looks much more convenient than a new method! Thanks! – MartyIX Jun 20 '10 at 12:10
  • @Dan Puzey: A fair observation. But if that's the case or not depends on the specifics of the problem, and on the relationship between A and B. It makes perfect sense in [some cases](http://stackoverflow.com/questions/1065355/forwarding-events-in-c). – Jordão Jun 21 '10 at 11:21
0

No, you can't, unless the code is in the class that declares the event. Events can only be fired from the declaring class. You probably have to consume an event with the arguments from both classes and in return fire the event, but you can't guarentee they will be fired at the same time, only about the same time, depending on the methods registered to each event, as they will be executed in the same thread.

Femaref
  • 60,705
  • 7
  • 138
  • 176
0

The fact that the events are defined in different classes means that they are not the same event, even though they may have the same signature. You can't fire events from two separate classes at once.

Amongst other things, consider that an event is typically fired from an instance of a class. Which instance of B.eventB would you fire when A.eventA occurs?

Dan Puzey
  • 33,626
  • 4
  • 73
  • 96