CHAPTER 8 WORKING WITH INTERFACES
// This class derives from System.Object and
// implements a single interface.
public class Pencil : IPointy
{...}
// This class also derives from System.Object
// and implements a single interface.
public class SwitchBlade : object, IPointy
{...}
// This class derives from a custom base class
// and implements a single interface.
public class Fork : Utensil, IPointy
{...}
// This struct implicitly derives from System.ValueType and
// implements two interfaces.
public struct PitchFork : ICloneable, IPointy
{...}
Understand that implementing an interface is an all-or-nothing proposition. The supporting type is
not able to selectively choose which members it will implement. Given that the IPointy interface defines
a single read-only property, this is not too much of a burden. However, if you are implementing an
interface that defines ten members (such as the IDbConnection interface shown earlier), the type is now
responsible for fleshing out the details of all ten abstract members.
For this example, insert a new class type named Triangle that is-a Shape and supports IPointy. Note
that the implementation of the read-only Points property simply returns the correct number of points
(3).
// New Shape derived class named Triangle.
class Triangle : Shape, IPointy
{
public Triangle() { }
public Triangle(string name) : base(name) { }
public override void Draw()
{ Console.WriteLine("Drawing {0} the Triangle", PetName); }
}
// IPointy implementation.
public byte Points
{
get { return 3; }
}
Now, update your existing Hexagon type to also support the IPointy interface type:
// Hexagon now implements IPointy.
class Hexagon : Shape, IPointy
{
public Hexagon(){ }
public Hexagon(string name) : base(name){ }
public override void Draw()
{ Console.WriteLine("Drawing {0} the Hexagon", PetName); }
287