|
Interface type checking |
Top Previous Next |
|
What is translated > Types > Records, Classes, Interfaces > Interfaces > Interface type checking Delphi provides several ways to test and cast interface references at runtime. The most common patterns involve the Supports function and the as and is operators. These enable safe checking and conversion between interfaces, especially when multiple interfaces are implemented by a single object.
Delphi2C# faithfully translates each of these constructs into idiomatic and semantically equivalent C#:
is-Operator
is Delphi Example
is operator — to check if a value implements a given interface
if Foo is IBar then IBar(Foo).DoSomething;
C# Translation
as operator — to cast with runtime type check (throws on failure)
if(Foo is IBar) ((IBar) Foo).DoSomething();
as Operator: Explicit Cast Used Instead
n Delphi, as throws an exception if the object does not support the interface. In C#, the as keyword returns null, which would silently fail if not checked.
To preserve Delphi semantics, Delphi2C# translates as using an explicit cast:
Delphi Example
Bar := Foo as IBar;
C# Translation
IBar Bar = (IBar)Foo;
This ensures functional compatibility and avoids subtle bugs caused by null dereferencing.
Supports-Function
Delphi Example
Supports function — to safely query interface support
if Supports(Foo, IBar, Bar) then Bar.DoSomething;
This code checks whether the Foo reference also implements IBar, and assigns it to Bar if successful.
C# Translation
if(Supports(Foo, out Bar)) Bar.DoSomething();
Delphi2C# emits the Supports<T> function if it was used in the original Delphi code
|
|
This page belongs to the Delphi2C# Documentation |
Delphi2C# home Content |