Bewerken

Delen via


Type testing and casting operators for interfaces

APPLIES TO: Business Central 2024 release wave 2 and later.

In the AL language, you can define interfaces, which is a syntactical contract that can be implemented by a nonabstract method. With Business Central 2024 release wave 2, you can also extend an interface, which allows for a more flexible and adaptable design. Learn more in 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. For this purpose, 2 operators is and as are availble.

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:

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;

Interfaces in AL
Extending interfaces in AL