CHAPTER 8 WORKING WITH INTERFACES
Now, when we make use of the BitmapImage, we are able to invoke each method at the object level
(as they are all public), as well as extract out a reference to each supported interface explicitly via
casting:
static void Main(string[] args)
{
Console.WriteLine("***** Simple Interface Hierarchy *****");
// Call from object level.
BitmapImage myBitmap = new BitmapImage();
myBitmap.Draw();
myBitmap.DrawInBoundingBox(10, 10, 100, 150);
myBitmap.DrawUpsideDown();
// Get IAdvancedDraw explicitly.
IAdvancedDraw iAdvDraw = myBitmap as IAdvancedDraw;
if(iAdvDraw != null)
iAdvDraw.DrawUpsideDown();
Console.ReadLine();
}
Source Code The InterfaceHierarchy proje ct is located under the Chapter 8 subdirectory.
Multiple Inheritance with Interface Types
Unlike class types, a single interface can extend multiple base interfaces, allowing us to design some very
powerful and flexible abstractions. Create a new Console Application project named
MIInterfaceHierarchy. Here is another collection of interfaces that model various rendering and shape
abstractions. Notice that the IShape interface is extending both IDrawable and IPrintable:
// Multiple inheritance for interface types is a-okay.
interface IDrawable
{
void Draw();
}
interface IPrintable
{
void Print();
void Draw(); // <-- Note possible name clash here!
}
// Multiple interface inheritance. OK!
interface IShape : IDrawable, IPrintable
{
int GetNumberOfSides();
}
300