There are a lot of articles about the use and abuse of FreeAndNil but there is one point I really don’t like about FreeAndNil: It is not type-safe. Let’s have a look at the implementation:

The comment describes the issue: “Be careful to only pass TObjects to this routine.” That’s why I would implement it in a different way:

This code is type-safe and don’t use pointer arithmetic. Maybe I will ask Marco if there is a chance to add the generic FreeAndNil method directly to TObject.

This entry was posted in Delphi, RAD Studio 10.2 Tokyo, Tips and Tricks, Uncategorized. Bookmark the permalink.

6 Responses to FreeAndNil

  1. Stefan Glienke says:

    You cannot add a method to a class that sets the instance variable to nil on which you are calling it unless it is some magic implemented into the compiler like .Free on ARC.

    Make this happen as it will solve not only this issue but countless others:

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.