exists()

The exists() function, similar to defined(), is a special compiler function that is evaluated not at runtime but at compile time, and is used by the compiler to conditionally compile (or not compile) certain sections of code, depending on the existence of a particular type or member. Like defined(), it can replace more traditional {$IF ...} or #if ... directives, and allows for conditional code that flows more freely.

The method takes a single parameter, which can either be an identifier, or a constant String containing an identifier. The function returns true at compile time if the given identifier exists in the current scope, or false if not.

Any code that would not execute due to a exists() check returning false – i.e. code that is in the if (or else) statement not being hit –; will be completely eliminated by the compiler, at compile time. Note that this code is allowed to refer to identifiers that are unknown for the current compile target – essentially allowing you to use defined() to compile conditional code for different platforms or APIs.

Boolean short-circuit is applied, so exists() can be combined in an if statement with other, runtime-evaluated conditions.

if exists(Foo.DoSomething) then
  Foo.DoSomething()
else
  writeLn("The 'Foo.DoSomething' method does not exist");
if (exists(Foo.DoSomething))
  Foo.DoSomething();
else
  writeLn("The 'Foo.DoSomething' method does not exist");
if exists(Foo.DoSomething) {
  Foo.DoSomething()
} else {
  writeLn("The 'Foo.DoSomething' method does not exist")
}
if (exists(Foo.DoSomething))
  Foo.DoSomething();
else
  writeLn("The 'Foo.DoSomething' method does not exist");

In the above example, the compiler would emit the call to Foo.DoSomething(), if the method indeed exists.

Like defined(), calls to exist() can be combined with "normal" at-runtime if conditions.

Using defined() outside of if

Note that while exists() can be called as a function in any context, it will only directly influence compiler behavior when used inside the expression of an if statement.

See Also