Omar Kooheji
Omar Kooheji

Reputation: 55760

In C#, how do you declare a subclass of EventHandler in an interface?

What's the code syntax for declaring a subclass of EventHandler (that you've defined) in an interface?

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 refers to 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?

Upvotes: 22

Views: 20781

Answers (2)

Mike Scott
Mike Scott

Reputation: 12463

Assuming C# 2.0 or later...

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

public interface IMyInterface
{
    event EventHandler<MyEventArgs> MyEvent;
}

Upvotes: 15

Marc Gravell
Marc Gravell

Reputation: 1062770

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;

Upvotes: 25

Related Questions