Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get a reference to a TQuery object created in a WITH statement? [duplicate]

Tags:

delphi

Possible Duplicate:
Reference object instance created using “with” in Delphi

One method that I use to create query objects in Delphi follows the first code sample. It gives me a reference to the object and I can then pass the object to a function.

procedure SomeProcedure;
var
  qry: TQuery;
begin
  qry := TQuery.Create(nil);

  with qry do
  begin
    Connection := MyConn;
    SQL.Text := 'SELECT * FROM PEOPLE';
    Open;

    funcDisplayDataSet(qry);
    Free;
  end;

end;

Is it also possible to do this in a WITH statement where your Create object in contained in the WITH statement?

procedure SomeProcedure;
begin
  with TQuery.Create(nil) do
  begin
    Connection := MyConn;
    SQL.Text := 'SELECT * FROM PEOPLE';
    Open;

    funcDisplayDataSet( ??? );  // Here I'm unsure how to pass the object created...
    Free;
  end;
end;

Can I pass this dynamic object to a function like `funcDisplayDataSet(TQuery)?

I just would like to know if this is possible. I'm not looking for a summary on why the WITH statement is bad or good. There are other posts on StackOver flow with that discussion.*

like image 773
Tim Koscielski Avatar asked Jan 18 '12 15:01

Tim Koscielski


2 Answers

That's not possible, in general, in a clean manner. Your options:

  1. Add a method to the class that returns Self.
  2. Stop using with and create a local variable for the instance.

Option 1 is viable if you have control over the class. But it leaves the class looking rather odd. Why would a class need an instance method that returned the instance? If you don't have control over the class then you could use a class helper as RRUZ suggests but I regard the use of class helpers as a last resort. I've never solved a problem with a class helper.

That leaves option 2. This would be how I would solve the problem.

like image 61
David Heffernan Avatar answered Nov 03 '22 00:11

David Heffernan


What about using a class helper ?

type
  TQueryHelper = class helper for TQuery
  public
    function Instance: TQuery;
  end;


function TQueryHelper.Instance: TQuery;
begin
  Result := Self;
end;

And use like this

   With TQuery.Create(nil) do
   begin
     SQL.Text:='Select * from OTGH';
     ShowMessage(Instance.SQL.Text);
   end;
like image 35
RRUZ Avatar answered Nov 03 '22 00:11

RRUZ