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
{
// ?????
}
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.
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;
}
Just expose the delegate as a property
public delegate void UpdateStatusEventHandler(string status);
public delegate void StartedEventHandler();
public interface IMyInterface
{
UpdateStatusEventHandler StatusUpdated {get; set;}
StartedEventHandler Started {get; set;}
}
Jon Skeet's answer is right, I just want to add a note.
Interfaces are not there for "reminding" you what to do, or what to include in your classes. Interfaces are means of abstraction, used in Object Oriented programming and design methods. Maybe you don't need an interface declaration at all, unless you want to see some concrete class instances as the interface elsewhere in your program (Abstraction).
If you want to enforce some coding standards in your project, you may want to try using code analysis tools (like in Visual Studio) - They allow extensions, that you can incorporate to add you own code analysis rules.
Using code analysis, if you "forget" to add the delegates (although I don't see the point of forgetting it, as if the delegate is not used, it's not needed) you'll get a warning / error.