tags:

views:

69

answers:

4

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.

A: 

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
+1  A: 

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
A: 

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
I have in class A reference to class B. I forgot to mention it, sorry.
MartyIX
+1  A: 

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
It seems it is what I was looking for. It looks much more convenient than a new method! Thanks!
MartyIX
While it does work, that looks like a code smell to me...
Dan Puzey
@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