Search code examples
delphivariable-assignmentself

Consequences of assigning self


Found a piece of code today, that I find a little smelly...

TMyObject.LoadFromFile(const filename: String);
begin
  if fileExists(filename) then
    self := TSomeObjectStreamer.ReadObjectFromFile(filename);
end;

If this code works, it will at least leak some memory, but does it work?
Is OK to assign to self in this manner?

What if the streamed object is of a different subclass then the original self?
What if the streamed object is of a different class with no common ancestor to the original self?


Solution

  • You can assign to Self, but it's only a local variable and you won't actually change anything outside the scope of that method. So that code is almost certainly not going to do what the original coder apparently thinks it's going to do.