Interfaces

               attributes? unsafe? access-modifier?
new?
interface interface-name 
[ : base-interface+ ]?
{ interface-members }

An interface is similar to a class, but with the following major differences:

  • An interface provides a specification rather than an implementation for its members. This is similar to a pure abstract class, which is an abstract class consisting of only abstract members.

  • A class and struct can implement multiple interfaces, while a class can inherit only from a single class.

  • A struct can implement an interface, but a struct cannot inherit from a class.

Earlier in this chapter, we defined polymorphism as the ability to perform the same operations on many types, as long as each type shares a common subset of characteristics. The purpose of an interface is precisely for defining such a set of characteristics.

An interface is comprised of a set of the following members:

  • Method

  • Property

  • Indexer

  • Event

These members are always implicitly public and implicitly abstract (and therefore virtual and nonstatic).

Defining an Interface

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 are intended to be implemented by a class or struct that implements the interface. Here is a very simple interface that defines a single method:

public interface IDelete {
   void Delete();
}

Implementing an Interface

Classes or structs that implement an interface may be said to “fulfill the contract ...

Get C# in a Nutshell 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.