views:

70

answers:

2

I'm trying to get around dual inheritance in C# by re-implementing one of the parent classes as an interface with extension methods.

The problem I'm encountering is that

event EventHandler<EventArgs> Disconnecting;

public static void OnDisconnected(this AutoConnectClientBase target)
        {
            target.ClientConnectionState = ConnectionState.Disconnected;
            target.Disconnected(target, EventArgs.Empty);
        } 

Can't be called in the extension methods. I get: *.Disconnecting can only appear on the left hand side of += or -=
While this makes perfect sense, in this case I wish it were not so.

What I'm looking for is a workaround that will permit me to access my interface's EventHandlers in the extension code. I'd like to keep it as simple as possible since the class I'm making into an interface is accessed by a large number of classes already and this is a change I'm reluctantly making in the first place.

+1  A: 

Not sure what the problem is here -- the code you show doesn't match the error you cite (no call to .Disconnecting.

public interface IInterface
{
    event EventHandler Event;
    EventHandler Handler { get; set; }
}

public class Class : IInterface
{
    public event EventHandler Event;
    public EventHandler Handler { get; set; }

}

public static class InterfaceExtensions
{
    public static void DoSomething(this IInterface i)
    {
        i.Event += (o, e) => Console.WriteLine("Event raised and handled");
        i.Handler(i, new EventArgs());
    }
}
Jay
oops Disconecting instead of Disconected, they're both events I mixed them up..
Jean-Bernard Pellerin
@Jean So what in my code is different from what you want to do?
Jay
the "event EventHandler Event" will give a compiler error when accessed from the extension method.
Jean-Bernard Pellerin
The code above gives no compiler error. You must, of course, declare the event as `public`.
Jay
A: 

I resolved this by doing the following:
Outside of the interface

public delegate EventHandler<EventArgs> MyEventHandler(object sender, EventArgs e);

Then inside the interface

event EventHandler<EventArgs> Disconnecting;

becomes

MyEventHandler Connected {get; set;}
Jean-Bernard Pellerin