The IfThen function may cause access violations if used to conditionally access an
object that could be nil.
While the IfThen function is conceptually similar to the ternary operator found in
other languages, IfThen does not perform short-circuit evaluation. Both arguments are
evaluated when the function is invoked, meaning that all code will be run regardless of the result
of the condition.
Use a long-form if condition instead, which does perform short-circuit evaluation:
function MyFunc: string; var Foo: TFoo; begin Foo := nil; Result := IfThen(Assigned(Foo), Foo.Bar, 'Baz'); end;
function MyFunc: string;
var
Foo: TFoo;
begin
Foo := nil;
if Assigned(Foo) then begin
Result := Foo.Bar;
end
else begin
Result := 'Baz';
end;
end;