Interfaces: Events or Delegates?

I understand it is not possible to define an event handler as part of an interface definition.
Should this then be done with delegates?

Could you describe what it is you’re trying to do? Maybe we can help you find the correct solution.

1 Like

I have a class that has methods and ‘uses’ events to 
 i’d like to define an interface.

The “
” is hiding a lot in that description. :grin: We’re going to need to know at least something about your scenario in order to advise.

1 Like

Doh!
I hava a class that raises events and has public methods. How do I create an interface for that class and can I use events or must i use delegates?

This sounds like you need to invert your approach - consider something like the observer pattern where objects interested in updates can be attached to your event generating object to receive those updates. You would define an interface for notification observers and then an attach method on the event generating class which accepts an instance of that interface. then you can generically inform objects that care about the events.

2 Likes

That’s typically not what interfaces are for. Interfaces are for making a set of methods that are common to a set of classes that are not related by inheritance.

Let’s say your app generated data but you didn’t want to limit yourself to a single format. You could create an Interface called “Writer” with a method of Write(data as string). Then for every class that could be a “writer” you apply the interface and you can then use them interchangeably using just the methods of the interface.

That doesn’t seem to be what you’re trying to do here though


If you have a class raising events, could you not just subclass it and add event handlers in your new subclass? This option only works if you can create your subclass inplace of the existing one. Just an option though,

I think we may need to back up a bit. What are you actually trying to accomplish? Leave aside any ideas of how you might do it. Just tell us what you want the code to accomplish.

1 Like