Converting an interface reference for implementing a class in Delphi 2010

Original author: Malcolm Groves
  • Transfer
Not all innovations in Delphi 2010 are big and noticeable. The team spent a lot of time implementing many additional features, fixes and improvements. Some of them may seem insignificant separately, but they not only have a significant effect on the whole, but also significantly add harmony to the product.

One of the features of Delphi 2010, which, it seems to me, will give rise to a lot of controversy, is the ability to cast an interface link back to the type of a class that implements this interface.

Let's imagine that we have an IMyInterface interface and a TMyClass class that implements this interface:

IMyInterface = interface
procedure Foo;

TMyClass = class(TInterfacedObject, IMyInterface)
 procedure Foo;
 procedure Bar;

Next, let's imagine that we were given a variable of type IMyInterface . What happens if we want to call Bar ? Trying to simply cast an interface reference to a TMyClass type will result in a compiler error.

The most common solution I've seen is to include in the interface a method that returns the type of the class, but it destroys the value of putting the interface in first place, binding the interface to a specific implementation. Moreover, it is disgusting.

Such techniques are no longer needed.

In Delphi 2010 you can use the is operatorin order to check whether an interface is implemented by a particular class, and if so, bring it to this class and use non-interface methods, properties, etc.

Moreover, if you try to cast an interface reference to the type of the class from which it was not actually obtained, the as operator will throw an EInvalidCast exception . Under the same conditions, a hard cast will return nil .

Now this code runs successfully:
if MyInterface is TMyClass then

Of course, this should be used with understanding. For example, the usual compiler warnings about saving the interface with reference counting and links to an object without counting references to the same instance remain valid.

You can help improve the translation.
Translators: r3code , debose , VesninAndrey

Also popular now: