Interfaces define what is referred to as a contract . Literally, an interface is a type that contains method, property, or event headers only, with no implementations . Interfaces can be inherited, which is a way of extending the contract, and interfaces can be implemented.
Interfaces themselves are never created, nor are they ever fleshed out and provided with an implementation. When a Visual Basic .NET class accepts an interface contract, the class must implement every member defined in the interface. This is the crux of the contractual obligation.
Some basic guidelines for defining interfaces exist to support the expectations consumers will have when they use your interfaces. Some of these guidelines are enforced by the interface idiom, and consequently you have to follow them. Other guidelines are suggestions that consumers will expect you to adhere to.
By applying all of these guidelines, you can define interfaces and examine some existing interfaces. Interfaces are not that hard to define or understand in practice. (Refer to the Comparing Abstract Classes to Interfaces section near the end of this chapter for a comparative discussion on inheriting abstract classes versus implementing interfaces.)
Defining an Interface
Interfaces are defined in a block statement with a header. Inside the interface are the method, property, and event signatures you deem essential to your interface. You have to have at least one member in an interface, but you are not required to use all these elements. Here is an example that demonstrates the grammatical aspects of interfaces.
Public Interface IFoo Sub Foo() End Interface
Suppose we want to know when a class supports GDI+ drawing. We could define an interface IDrawable that contains one method, Draw .
Public Interface IDrawable Sub Draw(ByVal G As Graphics) End Interface
Any class that implements the IDrawable interface would have to provide an implementation of the Draw method. From the signature ”it takes a Graphics object ”we can assume that a class implementing IDrawable would be able to create a graphical representation on a drawing surface represented by the Graphics object.
Interfaces are used all over the Common Language Runtime. For example, arrays and collections implement IEnumerable , which defines one member, GetEnumerator . GetEnumerator returns an object that implements IEnumerator . In turn , IEnumerator defines a common way of iterating over items in a list, collection, or array.