Jump to content

Recommended Posts

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

type
  TMyRecord = record
  strict private
    FIntValue1: Integer;
    FIntValue2: Integer;
    procedure SetIntValue(AValue: Integer);
  public
    property IntValue: Integer read FIntValue1 write SetIntValue;
    property IntValue2: Integer read FIntValue2 write FIntValue2;
  end;

  TMyClass = class //(TInterfacedObject, IMyClass)
  strict private
    FMyRecValue: TMyRecord;
    function GetMyRecValue: TMyRecord;
    procedure SetMyRecValue(const Value: TMyRecord);
  public
     property MyRecValue: TMyRecord read GetMyRecValue write SetMyRecValue;
  end;

{ TMyClass }

function TMyClass.GetMyRecValue: TMyRecord;
begin
    result := FMyRecValue;
end;

procedure TMyClass.SetMyRecValue(const Value: TMyRecord);
begin
    FMyRecValue := Value;
end;

{ TMyRecord }

procedure TMyRecord.SetIntValue(AValue: Integer);
begin
    FIntValue1 := AValue;
end;

begin
  try
    var MyTestClass := TMyClass.Create;
    try
       MyTestClass.MyRecValue.IntValue := 1;

       // This line gives an error: Left side cannot be assigned to
       //MyTestClass.MyRecValue.IntValue2 := 2;

       var TestValue1 := MyTestClass.MyRecValue.IntValue;
       //var TestValue2 := MyTestClass.MyRecValue.IntValue2;
       writeln(TestValue1);  // Shows Value 0       
       readln;
    finally
       MyTestClass.Free;
    end;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

what is going on here?

 

I Assigne value a value:  MyTestClass.MyRecValue.IntValue := 1;
Then read it back:    var TestValue1 := MyTestClass.MyRecValue.IntValue;
    
The TestValue1 is 0, I would expect it to be 1.

If I try to write to the IntValue2 without a setter medthod it will give an error: "Left side cannot be assigned to".

 

What am I missing?

Share this post


Link to post

 

MyTestClass.MyRecValue.IntValue := 1;

MyRecValue gives you a copy of the record, you have to write it back. Or use objects instead.

 

 

 

 

Share this post


Link to post

Since you are dealing with a record and not a class, your MyRecValue property getter is returning a COPY of the record. You can't modify the copy the way you are trying to do. You would need to have the property return a pointer to the record instead, or else switch to a class (in which case, your property can return an object pointer).

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×