liveBook · Manning

Interface

As explained in .NET in Action, Second Edition

An interface is a C# contract that specifies members an implementing type must provide.

An interface defines a contract: a class that implements it must provide the specified members. Interface methods and properties must be public. A class can implement multiple interfaces, but it can derive from only one base class. section 2.8

An abstract class is different: it can contain an incomplete implementation, with missing members marked abstract. It cannot be instantiated directly. Choose an interface when the important relationship is the contract a class fulfills, rather than a shared base-class implementation. section 2.8

An interface in a generic parameter

In command-line parsing, IEnumerable<string> specifies an enumerable of strings. IEnumerable is an interface implemented by arrays, lists, and other collections, so the parameter is not tied to just one collection type. section 2.8

Interfaces can also remove a direct dependency on one implementation. A card deck that depends on System.Random for shuffling can instead depend on a randomization interface. The application can then choose an implementation suited to the situation, giving it more control over shuffling. section 6.2.5

Figure 6.3 A class diagram of DeckOfCards with a dependency on an interface to perform randomization along with implementations of that interface

The class diagram shows the deck depending on an interface, with separate implementations supplying randomization. section 6.2.5

How .NET in Action, Second Edition covers it

How deep it goes
Defines implementation rules and contrasts abstract classes, then explains dependency inversion without listing a complete interface implementation.
Examples
Illustrates IEnumerable<string> in command-line parsing and an interface replacing System.Random in card shuffling.
What it assumes
Assumes familiarity with C# classes and methods while defining interface contracts and contrasting abstract classes.
What you can do after
Evaluate/understand when an interface lets an application choose among implementations instead of depending on one directly.
How it connects
Connects interfaces to abstract classes, generics, IEnumerable, and dependency inversion.

Also explained in

Compare how 7 books explain interface →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.