What is a good example of the power of interface events (declaring events inside interface)?
Most of the times I have seen only public abstract methods inside 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.
An interface can be created to define a contract containing members that classes that implement it must provide. Interfaces can define events, sometimes leading to classes that implement several interfaces being required to declare an event name twice.
One of the major advantages of Interface in C# is a better alternative to implement multiple inheritances. The interface enables the plug-and-play method. Complete Abstraction can be achieved by the implementation of Interface. Along with making our code easy to maintain, concept loose coupling can be achieved.
In C#, an interface is similar to abstract class. However, unlike abstract classes, all methods of an interface are fully abstract (method without body). We use the interface keyword to create an interface. For example, interface IPolygon { // method without body void calculateArea(); }
I used events to signal when a serial port received data.
Here is my interface.
public interface ISerialPortWatcher { event EventHandler<ReceivedDataEventArgs> ReceivedData; event EventHandler StartedListening; event EventHandler StoppedListening; SerialPortSettings PortOptions { set; } bool Listening { get; set; } void Stop(); void Start(); } public class ReceivedDataEventArgs : EventArgs { public ReceivedDataEventArgs(string data) { Data = data; } public string Data { get; private set; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With