Is it better to do if assigned(MyObj) then or if (MyObj <> nil) then [duplicate]

  • A+

This question already has an answer here:

When i read the modifications made in the original delphi source code (mostly in the firemonkey) I saw that embarcadero sometime replace if assigned(MyObj) then by if (MyObj <> nil) then. Is their any real reason to do this or it's simply purely cosmetic ?

For pointers, object references, dynamic arrays, interfaces, there is no difference. You can do either.

For method pointers there is a difference. The IDE form designer does some trickery with published method pointer properties, e.g. events. When these are nil the IDE form designer stores an index in the low two bytes of one of the pointers. If you were to test this against nil you would find that the value was not nil, which is not desired.

So you use Assigned which ignores the low two bytes. This is possible on Windows because memory addresses lower than 65536 are reserved and cannot be valid pointers. This is critical for code that runs in the IDE form designer, i.e. design time packages. Component writers must use Assigned in these situations.

Note that this only applies to the Win32 compiler. Since that is the only platform on which the IDE runs, that is the only platform where Assigned has this special behaviour.

Allen Bauer discusses this here: Assigned or not Assigned, that is the question...

One further point to make:

  • It is never wrong to use Assigned.
  • It is wrong to compare against nil when the subject is a method pointer that backs a published property, and your code runs at design time.

Personally, I always use Assigned because that gives consistency to the code. Further it means that you don't even have to consider whether or not the subject of the test is a single pointer type or a double pointer type, or whether your code ever runs in the designer.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: