tags:

views:

68

answers:

2

Hi, I have a question related to events (no, its not duplicate from my previous one). I am interested whether I can send an event to class without specifying direct method name. I cannot explain in english well, please look at the code:

class a
{
  public event eventhandler TEST;
  b _b=new b();
 TEST+=b_.MethodA(); //this is not useful for me since I need to know the method name that will be used by class B. }

class b
{ 
 MethodA();
}

I would need only to raise an event and let the class B owner (inside B class) to determine what method will be called. The only think I can think of is to pass the event or the class as an argument to class B constructor.

A: 

Assuming A does not know about B: If B knows about A, then B can add one of its methods to the event in A.

If on the other hand neither A nor B has knowledge about the other, but they are still somehow related in the program, then there must exist code elsewhere that relates them to each other and has knowledge of both. In that case, this external code should make the connection.

A a = new A();
B b = new B();
a.TEST += b.methodA();

Did that answer your question?

Josef Grahn
+1  A: 

If you want class B to determine how to handle the event, then it will need to have some way of advertising that it can do so. One simple way is to implement an interface - but then that means it can only have one handler. It would, however, mean that you could use any implementation of the interface and let it decide what to do. The interface would look like the event handler delegate signature, basically:

public interface IEventHandler
{
    void HandleEvent(object sender, EventArgs e);
}

Then you could do:

IEventHandler handler = new B(); // Assuming B implements IEventHandler
TestEvent += handler.HandleEvent;

But I can't think of any time I've really wanted to do this. Could you give us more information about the big picture?

Jon Skeet