Search code examples
c#.netevents

How to create wrapper over event in C#


Let's say I have this class:

public class someClassA
{
    Connector connector;

    public void SubscribeToEvent(IList<string> stockNames)
    {
        connector.OnEventReceived += SomeReceiverMethod;
    }

    private void SomeReceiverMethod(ReceivedData receivedData)
    {
        Console.WriteLine(receivedData);
    }
}

What I want to do is to get this received data in other class on subscribe

public class someClassB
{
   var classA = someClassA;
   someClassA.SomeSender += SomeReceiver;
}

How can I achieve that SomeSender from someClassB?


Solution

  • There are two basic ways

    1. Raise a new event:
    private void SomeReceiverMethod(ReceivedData receivedData)
    {
        DataReceived?.Invoke(this, receivedData);
    }
    public event EventHandler<ReceivedData> DataReceived;
    
    1. Forward the event registrations
    // EventReceivedDelegate needs to be the same type as OnEventReceived 
    public event EventReceivedDelegate EventReceived{
       add => connector.OnEventReceived += value;
       remove => connector.OnEventReceived -= value;
    }
    

    The former is more flexible since it allow you to do some processing of the data before raising the next event, as well as changing types etc. But it require a bit more code