views:

88

answers:

1

Hello, I'm currently developing an EventManager class to ensure that no events are left wired to dead WCF duplex clients, and also to control prevent multiple wiring from the same client to the one event.

Now basically, I'm what stuck with is trying to pass the event delegate to a function that will control the assignment like this.

var handler = new SomeEventHandler(MyHandler);
Wire(myObject.SomeEventDelegate, handler);

To call this:

private void Wire(Delegate eventDelegate, Delegate handler)
{
    // Pre validate the subscription.
    eventDelegate = Delegate.Combine(eventDelegate, handler);
    // Post actions (storing subscribed event delegates in a list)
}

Update

The code for SomeEventDelegate wrapper is:

public Delegate SomeEventDelegate
{
    get { return SomeEvent; }
    set { SomeEvent = (SomeEventHandler) value; }
}

event SomeEventHandler SomeEvent;

Obviously the delegate is not being returned to the myObject.SomeEventDelegate And I cannot return the Delegate from the method because I need some validation after too. Do you have any idea on how to do this?

BRGDS

+2  A: 

Use the C# ref parameter modifier:

var handler = new SomeEventHandler(MyHandler);
Wire(ref myObject.SomeEventDelegate, handler);

private void Wire(ref Delegate eventDelegate, Delegate handler)
{
    // Pre validate the subscription.
    eventDelegate = Delegate.Combine(eventDelegate, handler);
    // Post actions (storing subscribed event handlers in a list)
}

Note also that there exists some nice syntactic sugar (as of C# 2.0) for assigning and combining delegates (see this article, for example):

Wire(ref myObject.SomeEventDelegate, MyHandler);

private void Wire(ref Delegate eventDelegate, Delegate handler)
{
    // Pre validate the subscription.
    eventDelegate += handler;
    // Post actions (storing subscribed event handlers in a list)
}

It has been pointed out to me that ref only works with fields, not properties. In the case of a property, an intermediary variable can be used:

var tempDelegate = myObject.SomeEventDelegate;
Wire(ref tempDelegate, MyHandler);
myObject.SomeEventDelegate = tempDelegate;
Cameron
Note that it will only work if SomeeventDelegate is a field... Properties can't be passed as ref parameters
Thomas Levesque
hi there, the ref keyword doesn't work here because the myObject.SomeEventDelegate is just a wrapper property to make the event delegate accessible outside the its class.
gjsduarte
@Thomas: Ah, good point. I had forgotten about that. In that case, an intermediary variable can be used. Editing...
Cameron
Ok, I believe it works now! I changed the event declaration following the Steve Guidi suggestion and after I could use the ref keyword. Thank you all for your help!
gjsduarte