Best way to check if a Variable is nil?
delphi, pointers
Solution
It's usually the same... except when you check a function...
function mfi: TObject;
begin
Result := nil;
end;
procedure TForm1.btn1Click(Sender: TObject);
type
TMyFunction = function: TObject of object;
var
f: TMyFunction;
begin
f := mfi;
if Assigned(f) then
begin
ShowMessage('yes'); // TRUE
end
else
begin
ShowMessage('no');
end;
if f <> nil then
begin
ShowMessage('yes');
end
else
begin
ShowMessage('no'); // FALSE
end;
end;
With the second syntax, it will check the result of the function, not the function itself...
Problem
A common condition that all programs should do is to check if variables are assigned or not. Take the below statements: (1) ``` if Assigned(Ptr) then begin // do something end; ``` (2) ``` if Ptr <> nil then begin // do something end; ``` What is the difference between `Assigned(Ptr)` and `Ptr <> nil`?