Re: Access instance created in with .. do

Giganews Newsgroups
Subject:Re: Access instance created in with .. do
Posted by: Joanna Carter [TeamB] (joanna@not.for.spam)
Date:Wed, 21 Jun 2006

"Christian Gorski" <no.spam@no.spam.com> a écrit dans le message de news:
449953b0$…@newsgroups.borland.com...

| Is there any possibility to access the reference pointer to an instance
| of an object created in with .. do?
|
| For example, I want to call SomeFunc with the created instance of TObj:
|
| with TObj.Create do begin
|  SomeFunc(?);
|  Free;
| end;

First of all "with" is evil ! :-))

Second, if you really insist on using it, then you need to add a method,
that returns self, to the class that you are trying to use

TObj = class
...
public
  function GetThis: TObj;
  ...
end;

implementation

function TObj.GetThis: TObj
begin
  return self;
end;

Thirdly, if you are going to call free in the with block I suggest you also
include a correctly declared try..finally block inside it.

begin
  with TObj.Create do
  try
    SomeFunc(?);
  finally
    Free;
  end;
end;

But better still would be to do things properly and not have to mess up your
classes for the sake of a couple of extra keypresses when typing the code.

var
  obj: TObj;
begin
  obj := TObj.Create;
  try
    SomeFunc(obj);
  finally
    obj.Free;
  end;
end;

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer

Replies

In response to

Access instance created in with .. do posted by Christian Gorski on Wed, 21 Jun 2006