Link to home
Start Free TrialLog in
Avatar of fischermx
fischermxFlag for Mexico

asked on

Free and Nil..... or Nil and Free.....

Hi,

I have a basic Delphi question.

I've seen code where people use

FreeAndNil(MyObject);

Open in new window

Some times other people write
MyObject.Free();
MyObject := nil;

Open in new window



However the FreeAndNil function code is this:

procedure FreeAndNil(var Obj);
var
  Temp: TObject;
begin
  Temp := TObject(Obj);
  Pointer(Obj) := nil;
  Temp.Free;
end;

Open in new window



Which seems to first nil the object, then free it.
As opposite as what I've seen in other's people code where in separate lines they write Free first, then set it to Nil

Are both ways okey?
If not, why?
Please elaborate :)

ASKER CERTIFIED SOLUTION
Avatar of Ephraim Wangoya
Ephraim Wangoya
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
FreeAndNil was introduced in D5 to make life a little easier for the developer

Setting a reference to a object = nil also clears the reference count
allowing it to free the object > used with com objects
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This is a good resource for learning about the difference between Free and FreeAndNil...


Which is preferable: Free or FreeAndNil?
http://stackoverflow.com/questions/3159376/which-is-preferable-free-or-freeandnil
For what it's worth: I normally only use FreeAndNil if it has a documenting purpose. In other words, if the logic of the code will make use of the same object (or whatever) again. If this is not the case it has no purpose to use FreeAndNil() instead of Free().

So if I see a FreeAndNil() in my code, I know something special is going on and somewhere further down the logic a piece of code needs to know the state (freed or not) of an object for some reason.