Interfaces

Interfaces provide the capability to define contracts that can be implemented by classes or structures. This way, the contract and the implementation of specific functionality can be decoupled from one another. For example, given the following interfaces, one can define what it means to enumerate over “something,” whether that is a collection type or data received from a network socket:

interface IEnumerable{    IEnumerator GetEnumerator();}interface IEnumerator{    bool MoveNext();    object Current { get; }    void Reset();}

Now code can be written to deal with anything that obeys this contract—for example, to print the results of enumerating to the screen. This way, interfaces allow polymorphic code to be written, something we look ...

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