tags:

views:

818

answers:

4

What delphi function asserts that an object is not nil?

+8  A: 

Not sure what you mean but Assert(Assigned(MyObject)); is pretty short and easy to use.

knight_killer
+3  A: 

if Assigned(MyObject) then ...

Bruce McGee
+12  A: 

Like knight_killer pointed out above, you use the Assert() function, asserting that Assigned(obj) is true. Of course, like in most compiled languages, assertions are not executed (or even included in the compiler output) unless you've specifically enabled them, so you should not rely on assertions for release mode builds.

You can, of course, simply check against nil, a la Assert(obj <> nil). However, Assigned() produces the exact same compiler output and has the added benefit that it works on pointers to class methods too (which are in reality a pair of pointers, one to the method, and the other one to the class instance), so using Assigned() is a good habit to pick up.

Mihai Limbășan
Actually, in Delphi assertions are on by default and have to be specifically disabled.
Mason Wheeler
+6  A: 

Assigned(AObject) will tell you if an object is nil or not.

Perhaps worth mentioning is the fact that if you free an object using AObject.Free the Assigned will still return true. So make sure you free the object using FreeAndNil(AObject).

T. Kaltnekar