Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a delegate to an interface C#

I need to have some delegates in my class.

I'd like to use the interface to "remind" me to set these delegates.

How to?

My class look like this:

public class ClsPictures : myInterface {     // Implementing the IProcess interface     public event UpdateStatusEventHandler UpdateStatusText;     public delegate void UpdateStatusEventHandler(string Status);      public event StartedEventHandler Started;     public delegate void StartedEventHandler(); } 

I need an interface to force those delegates:

public interface myInterface {    // ????? } 
like image 321
Asaf Avatar asked Oct 16 '10 11:10

Asaf


People also ask

Can I declare delegate in interface?

It's the base of design in the Object Oriented Programming. These are basically declaring delegate types, so they don't belong in an Interface. You can use Event in Interface with Delegate type.

CAN interface have events and delegates in C#?

An interface method can accept a delegate as a parameter, no issues.

What is the difference between an interface and a delegate?

Interface calls are faster than delegate calls. An interface reference is a reference to an instance of an object which implements the interface. An interface call is not that different from an ordinary virtual call to an method. A delegate reference, on the other hand, is a reference to a list of method pointers.

Can we have event in interface?

An interface can declare an event. The following example shows how to implement interface events in a class. Basically the rules are the same as when you implement any interface method or property.


2 Answers

Those are declaring delegate types. They don't belong in an interface. The events using those delegate types are fine to be in the interface though:

public delegate void UpdateStatusEventHandler(string status); public delegate void StartedEventHandler();  public interface IMyInterface {            event UpdateStatusEventHandler StatusUpdated;         event StartedEventHandler Started; } 

The implementation won't (and shouldn't) redeclare the delegate type, any more than it would redeclare any other type used in an interface.

like image 158
Jon Skeet Avatar answered Oct 07 '22 20:10

Jon Skeet


Since .NET 3.5 you can also use the System.Action delegates, without the need to declare your own type.

This would result in the following interface:

public interface myInterface {           // Implementing the IProcess interface    event Action<String> UpdateStatusText;     event Action Started; } 
like image 41
DELUXEnized Avatar answered Oct 07 '22 21:10

DELUXEnized