views:

1337

answers:

2

Whats the correct format for declaring an event handler in an interface if you are using a custom subclass of EventHandler rather than the base EventHandler class.

I create the EventHandler subclass MyEventHandler for example in the delegate declaration, but you can't declare a delegate in an interface...

When I ask Visual Studio to Extract an interface it references the EventHandler in IMyClassName as MyClassName.MyEventHandler which obviously plays havoc with type coupling.

I'm assuming there is a simple way to do this, do I have to Explicitly declare my event handler in a separate file?

+3  A: 

Well, you need to define the args and possibly delegate somewhere. You don't need a second file, but I'd probably recommend it... but the classes should probably not be nested, if that was the original problem.

The recommendation is to use the standard "sender, args" pattern; there are two cmmon approaches:

1: declare an event-args class separately, and use EventHandler<T> on the interface:

public class MySpecialEventArgs : EventArgs {...}
...
EventHandler<MySpecialEventArgs> MyEvent;

2: declare an event-args class and delegate type separately:

public class MySpecialEventArgs : EventArgs {...}
public delegate void MySpecialEventHandler(object sender,
    MySpecialEventArgs args);
....
event MySpecialEventHandler MyEvent;
Marc Gravell
Thanks it looks like that works.
Omar Kooheji
+3  A: 

Assuming C# 2.0 or later...

public class MyEventArgs: EventArgs
{
    // ... your event args properties and methods here...
}

public interface IMyInterface
{
    event EventHandler<MyEventArgs> MyEvent;
}
Mike Scott
Thanks that works a treat.
Omar Kooheji