Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 216
Omar Kooheji Avatar asked Feb 25 '09 12:02

Omar Kooheji


People also ask

What does != Mean in C?

The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .

What is operators in C?

C operators are one of the features in C which has symbols that can be used to perform mathematical, relational, bitwise, conditional, or logical manipulations. The C programming language has a lot of built-in operators to perform various tasks as per the need of the program.

What is the use of in C?

In C/C++, the # sign marks preprocessor directives. If you're not familiar with the preprocessor, it works as part of the compilation process, handling includes, macros, and more.


2 Answers

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; 
like image 92
Marc Gravell Avatar answered Sep 16 '22 16:09

Marc Gravell


Assuming C# 2.0 or later...

public class MyEventArgs: EventArgs {     // ... your event args properties and methods here... }  public interface IMyInterface {     event EventHandler<MyEventArgs> MyEvent; } 
like image 26
Mike Scott Avatar answered Sep 20 '22 16:09

Mike Scott