This is a mirror of official site: http://jasper-net.blogspot.com/

C# Interface Events

| Sunday, October 10, 2010
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.

Declaring Events in Interfaces
  In a previous article that formed part of the C# Object-Oriented Programming tutorial, I described the use of interfaces, which can be used to create contracts for classes. In that article were examples of interfaces that enforced the inclusion of methods and properties in the classes that implemented them. Interfaces are not limited to defining methods and properties. They can include other member types, such as events.
In this article we will look at how events can be included in interfaces and how they are added to classes using implicit or explicit implementation. We will also examine the rare but important situation where a class implements two interfaces that each contain an event with the same name.

Defining an Interface Event
  To demonstrate the use of events within interfaces we need an interface to work with. To follow the examples, create a new console application and add the following interface to the project. This interface includes an event named, "Notify". The NotifyNow method is an artificial item that we will use to force the event to be raised.

public interface INotify
{
   event EventHandler Notify;
   void NotifyNow();
}

Implementing an Interface Event
  We can now create a class that implements the INotify interface. The Test class defined below achieves this by declaring the event as a public member. The public NotifyNow method simply calls the private OnNotify method, which in turn raises the event if there are any subscribers. The syntax of the event and the OnNotify method that raises it are no different to that of an event that is not defined in an interface.

Read more: Black Wasp

Posted via email from .NET Info

0 comments: