RAD Studio |  |

Using the as Operator with Interfaces
See Also
Collapse All

Classes that implement interfaces can use the as operator for dynamic binding on the interface. In the following example,

Copy Code

    procedure PaintObjects(P: TInterfacedObject)
    var
      X: IPaint;
    begin
      X := P as IPaint;
    { statements }
    end;

the variable P of type TInterfacedObject, can be assigned to the variable X, which is an IPaint interface reference. Dynamic binding makes this assignment possible. For this assignment, the compiler generates code to call the QueryInterface method of P's IInterface interface. This is because the compiler cannot tell from P's declared type whether P's instance actually supports IPaint. At runtime, P either resolves to an IPaint reference or an exception is raised. In either case, assigning P to X will not generate a compile-time error as it would if P was of a class type that did not implement IInterface.

When you use the as operator for dynamic binding on an interface, you should be aware of the following requirements:

- Explicitly declaring IInterface: Although all interfaces derive from IInterface, it is not sufficient, if you want to use the as operator, for a class to simply implement the methods of IInterface. This is true even if it also implements the interfaces it explicitly declares. The class must explicitly declare IInterface in its interface list.
- Using an IID: Interfaces can use an identifier that is based on a GUID (globally unique identifier). GUIDs that are used to identify interfaces are referred to as interface identifiers (IIDs). If you are using the as operator with an interface, it must have an associated IID. To create a new GUID in your source code you can use the Ctrl+Shift+G editor shortcut key.

See Also

Using Interfaces with Procedures

Implementing IInterface

Using Interfaces Across the Hierarchy

Memory Management of Interface Objects

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!