1

I have C# class for which I am creating multiple objects for that class.

Now, I have one event for which all the objects of that class needs perform operation(In other words, I need to call specific function of all the object for that event).

The event is external to class.

Event is caused when I receive data from some external input in other class B or class C and I have to send that data to all the object of class A using method or event.

I need to raise event from multiple class B/C/D in class A.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
H. Mahida
  • 2,356
  • 1
  • 12
  • 23
  • Possible duplicate of [How to subscribe to other class' events in c#?](http://stackoverflow.com/questions/913374/how-to-subscribe-to-other-class-events-in-c) – Lews Therin Oct 07 '15 at 14:30
  • @Sylverac , Thanks for link but I need to raise event from multiple classes to single class. !! – H. Mahida Oct 08 '15 at 04:18
  • @H.Mahida - Can you please show the code that you currently have for your object and for the code that raises the external event? – Enigmativity Oct 08 '15 at 05:04

1 Answers1

2

A modern, clean way to handle this would be to use Reactive Extensions.

Suppose your event argument is of type EArg.

Place a static Subject<EArg> in your class A.

private static readonly Subject<EArg> subject = new Subject<EArg>();

Each instance of A can observe this IObservable<T> and act on it.

public ClassA()    // Constructor
{
   subject.Subscribe(HandleEvent);
}

private void HandleEvent(EArg arg)
{
   // ... 
}

When any external class calls (perhaps via a static method on class A) the OnNext method, all of the instances of class A can respond to it.

public static void RaiseEvent(EArg arg)
{
   subject.OnNext(arg);
}

Essentially you are looking for a pub-sub mechanism and Reactive Extensions is the cleanest way to achieve that.

NB, don't expose the Subject externally, see for example Why are Subjects not recommended in .NET Reactive Extensions?

Community
  • 1
  • 1
Ian Mercer
  • 38,490
  • 8
  • 97
  • 133
  • 2
    I totally agree than Rx is an excellent fit here, but your answer is a bit confusing and not overly convincing. I think you should explain the relationship between `Subject` and `IObservable`, and also provide some sample code to show how it would work for the OP. – Enigmativity Oct 08 '15 at 05:03
  • Maybe, but let's see what the OP says. We really more information about what the event arguments are in order to define the appropriate Subject. – Ian Mercer Oct 08 '15 at 05:40