Interfaces Basics


On occasions it is useful to define what must be done but not how to do it. An example of this has already been encountered with abstract methods, where no implementation of the method is given in the base class. An abstract method defines the form of the interface of the method but does not provide an implementation. An interface is a class where all methods are abstract. Interfaces do not contain any fields (data). In an interface, no method can include a body. So an interface provides no implementation details whatsoever - it purely concentrates on the form of the interface methods. In addition to methods, interfaces can define indexers, properties and events. Interfaces cannot define constructors, a destructor or operators and no method can be declared as static.

Perhaps one of the main reasons why interfaces are so frequently used is that they have special properties with regards to inheritance. While single inheritance restricts a derived class to having a single base class, a derived class can inherit from an unlimited number of interfaces.

To implement an interface, a class must provide implementations of all the methods that are found in the interface. Each class provides a particular implementation and different classes implementing the same interface may provide quite different implementations of the methods. Code that has no knowledge of the details of the implementations may make use of the interface as incorporated into multiple classes.

Interfaces are declared using the keyword interface. A simplified syntax of declaring an interface (excluding properties, indexers and events) is shown below.

interface name
{
 return-type method-name1(parameter-list);
 return-type method-name2(parameter-list);
 // ...
 return-type method-nameN(parameter-list);
}

The name of the interface is specified by name. The declaration of methods provides only the signature and return type (i.e. no body). Each method is implicitly abstract and public. The public access specifier is not required and not permitted.

An example of an interface is shown below.

public interface ISequence
{
    uint Next();         // Return the next number
    void Reset();        // Reset to start
    void Start(uint s);  // Set starting point
}

The name of the interface is ISequence. It is customary to name interfaces with an I prefix, and .Net interfaces satisfy this convention.