Posts

Showing posts from September, 2014

Difference between Free and FreeAndNil in Delphi: What to use when?

Difference between Free and FreeAndNil in Delphi: What to use when? Free and FreeAndNil are the main concepts of memory management in Delphi. FreeAndNil is a function declared in the SysUtils unit and was introduced in Delphi 5. Below is the implementation of FreeAndNil: procedure FreeAndNil(var Obj); var   Temp: TObject; begin   Temp := TObject(Obj);   Pointer(Obj) := nil;   Temp.Free; end; Difference between Free and FreeAndNil:  FreeAndNil first sets the object reference to nil and then frees the object.  When to use FreeAndNil instead of Free? If you want a rational answer, the question to ask is, why would you want to set an object reference to nil once you’re done with it?  And there’s only one good reason to ever do that: If you want to reuse the variable later.  There are some times when you’ll have an object that may or may not be initialized. If it’s not, then the variable will be nil, and if you find it’s nil, then you create it before using it.  This is a pretty common pat