Implementing Interface References

Interface reference variables allow you to call interface methods without knowing at compile time where the interface is implemented. But they are subject to the following:

  • An interface-type expression gives you access only to methods and properties declared in the interface, not to other members of the implementing class.
  • An interface-type expression cannot reference an object whose class implements a descendant interface, unless the class (or one that it inherits from) explicitly implements the ancestor interface as well.

For example, type

IAncestor = interface end;

IDescendant = interface(IAncestor) procedure P1;


TSomething = class(TInterfacedObject, IDescendant) procedure P1; procedure P2;


D: IDescendant; A: IAncestor; begin

D := TSomething.Create; // works! A := TSomething.Create; // error D.P1; // works! D.P2; // error end;

In this example, A is declared as a variable of type IAncestor. Because TSomething does not list IAncestor among the interfaces it implements, a TSomething instance cannot be assigned to A. But if we changed TSomething's declaration to

TSomething = class(TInterfacedObject, IAncestor, IDescendant)

the first error would become a valid assignment. D is declared as a variable of type ¡Descendant. While D references an instance of TSomething, we cannot use it to access TSomething's P2 method, since P2 is not a method of ¡Descendant. But if we changed D's declaration to

D: TSomething;

the second error would become a valid method call.

On the Win32 platform, interface references are typically managed through reference-counting, which depends on the _AddRef and _Release methods inherited from Ilnterface. These methods, and reference counting in general, are not applicable on the .NET platform, which is a garbage collected environment. Using the default implementation of reference counting, when an object is referenced only through interfaces, there is no need to destroy it manually; the object is automatically destroyed when the last reference to it goes out of scope. Some classes implement interfaces to bypass this default lifetime management, and some hybrid objects use reference counting only when the object does not have an owner.

Global interface-type variables can be initialized only to nil.

To determine whether an interface-type expression references an object, pass it to the standard function Assigned.

Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook

Post a comment