Implementing an Interface

The syntax for defining an interface is very similar to the syntax for defining a class:

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

Tip

The optional attributes are beyond the scope of this book. In short, every .NET application contains code, data, and metadata. Attributes are objects that are embedded in your program (invisible at runtime) and contain metadata—that is, data about your classes and your program. You don’t need to worry about them for our purposes here.

Access modifiers (public, private, and so forth) work just as they do with classes. (See Chapter 7 for more about access modifiers.) The interface keyword is followed by an identifier (the interface name). It is recommended (but not required) to begin the name of your interface with a capital I (IStorable, ICloneable, IGetNoKickFromChampagne, and so on). We will discuss the optional base list later in this chapter.

Now, suppose you are the author of a Document class, which specifies that Document objects can be stored in a database. You decide to have Document implement the IStorable interface. It isn’t required that you do so, but by implementing the IStorable interface, you signal to potential clients that the Document class can be used just like any other IStorable object. This will, for example, allow your clients to add your Document objects to an array of IStorable references:

IStorable[] myStorableArray = new IStorable[3];

As we discussed earlier, ...

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