Understand type testing and casting operators for interfaces
In the AL language, you can define interfaces, which is a syntactical contract that can be implemented by a nonabstract method. Since Business Central 2024 release wave 2, you can also extend an interface, which allows for a more flexible and adaptable design. For more information, see Extending interfaces in AL.
In connection with the extensibility of interfaces, it's useful to be able to do type testing and casting of interfaces. Two new operators, 'is' and 'as', have been added to facilitate these operations. The 'is' keyword checks if an interface is of a specific type, which is useful for ensuring type safety within code. The 'as' keyword, on the other hand, attempts to cast an interface to another interface. These operators improve the extensibility and usefulness of interfaces in AL and align with the broader programming practice of ensuring that systems are built with future growth and adaptability in mind, allowing for seamless updates and maintenance.
Type testing with the 'is' operator
Type testing with the 'is' operator is useful when extending interfaces, because it allows you to test whether an instance of an interface or the content of a variant supports a specific interface.
Here’s the syntax for using the 'is' keyword:
procedure TestInterface(intf: Interface IFoo)
begin
if intf is IBar then
Message('I also support IBar');
end;
You can also use the is operator with variants:
al-languageCopy
procedure TestVariant(v: Variant)
begin
if v is IBar then
Message('I support IBar');
end;
Casting with the 'as' operator
The 'as' operator is used for casting an instance of an interface to a specific interface. If the source interface doesn't implement the target interface, it throws an error at runtime.
Here’s an example:
procedure CastInterface(intf: Interface IFoo): Interface IBar
begin
exit(intf as IBar); // Throws an error if 'intf' doesn't implement 'IBar'
end;
Similarly, the 'as' keyword works with variants:
procedure CastInterface(v: Variant): Interface IBar
begin
exit(v as IBar); // Throws an error if 'v' doesn't implement 'IBar'
end;