Talk:System.Assigned

From RAD Studio API Documentation
Jump to: navigation, search

In answer to a question about why to use Assigned, I answered the following

AFAIK, the main reason to use Assigned is that it works properly with event pointers (i.e. procedure ... of object). Object, Interface, and other "plain" pointers are simply one value (a single pointer). In those cases, Assigned(Foo) and Foo <> nil are identical. Events are funny, though, in that they encapsulate two pointers: one that points to the code to execute and another that points to the object to execute it on. For example, the OnClick of a button pointing to a method of the form it's on (e.g. TForm1.Button1Click) will hold a pointer to the method (the code for TForm1.Button1Click) and also a pointer to the instance of the form the button is on. Assigned passed an event checks that both pointers are non-nil. If you just use <> nil with an event it will compare against just one of those pointers (I don't recall which, the code pointer, I think, but I could be wrong) so Assigned is typically what you want with events.

There is one more reason to use Assigned, which is a bit more subtle. Assigned will always check its argument against nil, even if that argument is a function-pointer where the pointed-to function is a function that returns a pointer (i.e. TFunc = function: Pointer). If you just check <> nil, Delphi will call the function and compare its result against nil. If you call Assigned, however, the function won't be called, rather the function-pointer itself will be checked for its nil-ness. For example, the following program:

 program Project1;
 
 {$APPTYPE CONSOLE}
 
 function Foo: Pointer;
 begin
   Result := nil;
 end;
 
 type
   TFooFunc = function: Pointer;
 var
   FooFunc: TFooFunc = Foo;
 begin
   Writeln('FooFunc <> nil:    ', FooFunc <> nil);
   Writeln('Assigned(FooFunc): ', Assigned(FooFunc));
 end.

Writes out:

 FooFunc <> nil:    FALSE
 Assigned(FooFunc): TRUE


Thank you for your input! Your suggestions have been added to our work queue. -- Denisa Tibeica