Best way to check if a Variable is nil?

后端 未结 2 1686
遇见更好的自我
遇见更好的自我 2020-12-11 14:44

A common condition that all programs should do is to check if variables are assigned or not.

Take the below statements:

(1)

         


        
相关标签:
2条回答
  • 2020-12-11 15:07

    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...

    0 讨论(0)
  • 2020-12-11 15:08

    As far as performance, there is no difference. I personally prefer the second form as I find that humans can parse the meaning quicker.

    0 讨论(0)
提交回复
热议问题