Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

What does the "with" command do?

Delphi - The Basics

What does the "with" command do?

by  djjd47130  Posted    (Edited  )
The with command is a block which changes the context of your code. For example, when you're working in a procedure which is declared in TForm1, the 'Context' is of TForm1. But when you add a 'with' block, the context is changed to whatever you put in your 'with' command.

Here's an example of an ordinary create/free scenario...

Code:
procedure TForm1.Button1Click(Sender: TObject);
var
  B: TBitmap;
begin
  B:= TBitmap.Create;
  try
    B.Width:= 100;
    B.Height:= 100;
    B.Canvas.Pen.Style:= psSolid;
    B.Canvas.Pen.Color:= clRed;
    B.Canvas.Pen.Width:= 3;
    B.Canvas.Brush.Style:= bsSolid;
    B.Canvas.Brush.Color:= clMaroon;
    B.Canvas.Ellipse(0, 0, 100, 100);
  finally
    B.Free;
  end;
end;

Now this works perfectly fine. But there's a way of using the 'with' command to where you don't even need to declare 'B: TBitmap'...

Code:
procedure TForm1.Button1Click(Sender: TObject);
begin
  with TBitmap.Create do begin
    try
      Width:= 100;
      Height:= 100;
      Canvas.Pen.Style:= psSolid;
      Canvas.Pen.Color:= clRed;
      Canvas.Pen.Width:= 3;
      Canvas.Brush.Style:= bsSolid;
      Canvas.Brush.Color:= clMaroon;
      Canvas.Ellipse(0, 0, 100, 100);
    finally
      Free;
    end;
  end;
end;

And you can also wrap the Canvas like this as well...

Code:
procedure TForm1.Button1Click(Sender: TObject);
begin
  with TBitmap.Create do begin
    try
      Width:= 100;
      Height:= 100;
      with Canvas do begin
        Pen.Style:= psSolid;
        Pen.Color:= clRed;
        Pen.Width:= 3;
        Brush.Style:= bsSolid;
        Brush.Color:= clMaroon;
        Ellipse(0, 0, 100, 100);
      end;
    finally
      Free;
    end;
  end;
end;

Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top