Interfaces

An interface is similar to a class, but it provides a specification rather than an implementation for its members. An interface is special in the following ways:

  • A class can implement multiple interfaces. In contrast, a class can inherit from only a single class.

  • Interface members are all implicitly abstract. In contrast, a class can provide both abstract members and concrete members with implementations.

  • Structs can implement interfaces, whereas a struct cannot inherit from a class.

An interface declaration is like a class declaration, but it provides no implementation for its members, since all its members are implicitly abstract. These members will be implemented by the classes and structs that implement the interface. An interface can contain only methods, properties, events, and indexers, which not coincidentally, are precisely the members of a class that can be abstract.

Here is a slightly simplified version of the IEnumerator interface, defined in System.Collections:

public interface IEnumerator
{
  bool MoveNext();
  object Current { get; }
}

Interface members are always implicitly public and cannot declare an access modifier. Implementing an interface means providing a public implementation for all its members:

internal class Countdown : IEnumerator
{
  int count = 11;
  public bool MoveNext()  { return count−− > 0 ;  }
  public object Current   { get { return count; } }
}

You can implicitly cast an object to any interface that it implements:

IEnumerator e = new Countdown(); while (e.MoveNext()) ...

Get C# 4.0 Pocket Reference, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.