Interfaces

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

An interface is like a class, but with these 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; a class can inherit only from a single class.

  • A struct can implement an interface; a struct can’t inherit from a class.

In Section 2.9, 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 comprises one or more methods, properties, indexers, and events. These members are always implicitly public and implicitly abstract (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’s a 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 of the interface.” In this example, GUI controls that ...

Get C# Essentials 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.