Chapter 8. Interfaces

An interface is a contract that guarantees to a client how a class or struct will behave (I'll just use the term class for the rest of this chapter, though everything I say will apply to structs as well).

When a class implements an interface, it tells any potential client "I guarantee I'll support all the methods, properties, events, and indexers of the named interface." (See Chapter 4 for information about methods and properties, Chapter 12 for information about events, and Chapter 9 for coverage of indexers.) See also the sidebar "Abstract Class Versus Interface Versus Mix-Ins."

These contracts are made manifest using the interface keyword, which declares a reference type that encapsulates the contract.

When you define an interface, you may define methods, properties, indexers, and events that will (and must!) be implemented by any class that implements the interface.

Tip

Java programmers take note: C# doesn't support the use of constant fields (member constants) in interfaces. The closest analog is the use of enumerated constants (enums).

In this chapter, you will learn how to create, implement, and use interfaces. You'll learn how to implement multiple interfaces, and how to combine and extend interfaces, as well as how to test whether a class has implemented an interface.

Defining and Implementing an Interface

The syntax for defining an interface is as follows:

[attributes] [access-modifier] interface interface-name[:base-list]
{interface-body}

Don't worry about ...

Get Programming C# 3.0, 5th 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.