Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert EventArgs when wiring events?

Tags:

c#

.net

events

In .NET applications, normally events are wired this way:

    public event EventHandler<ChangeEventArgs> OnChange
    {
        add { _dependency.OnChange += value; }
        remove { _dependency.OnChange -= value; }
    }

However this only works if the events being wired have the same event handler. In my current case, the original event args is proprietary of a library, and I don't want to expose that to the client code. So I have some kind of adapter (ChangeEventArgs). How can I use the code above to convert the event args? I imagine something like below (but below code doesn't work)

    public event EventHandler<ChangeEventArgs> OnChange
    {
        add { _dependency.OnChange += Convert(value); }
        remove { _dependency.OnChange -= Convert(value); }
    }

or

    public event EventHandler<ChangeEventArgs> OnChange
    {
        add { _dependency.OnChange += value(this, Convert(args)); }
        remove { _dependency.OnChange -= value(this, Convert(args)); }
    }
like image 528
Louis Rhys Avatar asked Sep 18 '12 11:09

Louis Rhys


1 Answers

Try this:

public class SomeClassAdapter
{
    private readonly SomeClass obj;

    public SomeClassAdapter(SomeClass obj)
    {
        this.obj = obj;
        this.obj.SomeEvent += HandleSomeClassSomeEvent;
    }

    private void HandleSomeClassSomeEvent(object sender, SomeEventArgs args)
    {
        OnSomeEvent(ConvertEventArgs(args));
    }

    private MyEventArgs ConvertEventArgs(SomeEventArgs args)
    {
        // the magic goes here...
    }

    protected virtual void OnSomeEvent(MyEventArgs args)
    {
        var handler = SomeEvent;
        if (handler != null)
        {
            handler(this, args);
        }
    }

    public event EventHandler<MyEventArgs> SomeEvent;
}

Update.
This code uses more complex version of adapter pattern, than your code does. SomeClassAdapter is an adapter for SomeClass (it has SomeClass instance in its private field obj).

Client code subscribes to my SomeClassAdapter.SomeEvent. My code, in turn, subscribes to SomeClass.SomeEvent. When SomeClass.SomeEvent is fired, my event handler (HandleSomeClassSomeEvent) is called. This event handler converts SomeEventArgs to MyEventArgs and raises SomeClassAdapter.SomeEvent.

So, we have the chain: SomeClass.SomeEvent -> HandleSomeClassSomeEvent -> SomeClassAdapter.SomeEvent. Looks like "event proxy".

like image 88
Dennis Avatar answered Sep 28 '22 20:09

Dennis