CHAPTER 8 WORKING WITH INTERFACES
// Error! Interfaces do not have constructors!
public IPointy() { numbOfPoints = 0;};
// Error! Interfaces don't provide an implementation of members!
byte GetNumberOfPoints() { return numbOfPoints; }
}
In any case, this initial IPointy interface defines a single method. However, .NET interface types are
also able to define any number of property prototypes. For example, let’s update the IPointy interface to
use a read-only property rather than a traditional accessor method:
// The pointy behavior as a read-only property.
public interface IPointy
{
// A read-write property in an interface would look like:
// retType PropName { get; set; }
//
// while a write-only property in an interface would be:
// retType PropName { set; }
byte Points { get; }
}
Note Interface types can also contain event (see Chapter 10) and indexer (see Chapter 11) definitions.
Interface types are quite useless on their own, as they are nothing more than a named collection of
abstract members. For example, you can’t allocate interface types as you would a class or structure:
// Ack! Illegal to allocate interface types.
static void Main(string[] args)
{
IPointy p = new IPointy(); // Compiler error!
}
Interfaces do not bring much to the table until they are implemented by a class or structure. Here,
IPointy is an interface that expresses the behavior of “having points.” The idea is simple: some classes in
the shapes hierarchy have points (such as the Hexagon), while others (such a s the Circle) do not.
Implementing an Interface
When a class (or structure) chooses to extend its functionality by supporting interfaces, it does so using a
comma-delimited list in the type definition. Be aware that the direct base class must be the first item
listed after the colon operator. When your class type derives directly from System.Object, you are free to
simply list the interface(s) supported by the class, as the C# compiler will extend your types from
System.Object if you do not say otherwise. On a related note, given that structures always derive from
System.ValueType (see Chapter 4), simply list each interface directly after the structure definition.
Ponder the following examples:
286