`With SomeProperty Do` allows access to private and strict private member fields, and circumvents Setter procedure, but shouldnt.
This does not compile in FPC or Delphi, because the left side is a property result (a rvalue) and therefore not an assignable target:
Shape.Center.X := 5;
This behaviour is correct, expected and required, but the following is not.
This is equivalent and should not compile. Nevertheless it compiles in FPC (but not in current Delphi 11):
with Shape.Center do X := 5;
At first sight this seems to work, but please read the discussion and code examples below. If the code is somewhat modified and enhanced, it still compiles but gives wrong result at runtime.
It cannot work, because the left side of the assignment is an rvalue, or a temporary copy of fCenter and not a reference to fCenter.
//Compiler used: Verbose: Free Pascal Compiler version 3.3.1-12796-gf721210638 [2023/06/23] for x86_64
// Verbose: Target OS: Win64 for x64
{$mode delphi} //Mode delphi or mode objfpc does not change behavior
program Project1;
uses
Types;
type
TShape=class
strict private
fCenter : TPoint;
procedure pset(p:Tpoint);
public
property Center : TPoint read fCenter write pset;
end;
procedure TShape.pset(p:Tpoint); // <-- This Setter is not called!
begin
fCenter := p;
writeln(p.X);
end;
var
Shape : TShape;
X:integer=10;
begin
Shape:=TShape.Create;
with Shape.Center do X:=5; //This compiles and runs in FPC, but shouldnt.
//doesnt compile in Delphi 11, regardless if the field is made public.
//Delphi says: [dcc32 Error] Project8.dpr(25): E2064 Left side cannot be assigned to
//Access to Center.X should not circumvent the setter procedure
//So this should be an Error!
Writeln(shape.Center.X); // This prints "5";
readln;
Shape.Free;
end.
Edited by Peter Heckert