Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi: Records in Classes

Following situation:

type
  TRec = record
    Member : Integer;
  end; 

  TMyClass = class
  private
    FRec : TRec;
  public
    property Rec : TRec read FRec write FRec;
  end;

The following doesn't work (left side cannot be assigned to), which is okay since TRec is a value type:

MyClass.Rec.Member := 0;

In D2007 though the following DOES work:

with MyClass.Rec do
  Member := 0;

Unfortunately, it doesn't work in D2010 (and I assume that it doesn't work in D2009 either). First question: why is that? Has it been changed intentionally? Or is it just a side effect of some other change? Was the D2007 workaround just a "bug"?

Second question: what do you think of the following workaround? Is it safe to use?

with PRec (@MyClass.Rec)^ do
  Member := 0;

I'm talking about existing code here, so the changes that have to be made to make it work should be minimal.

Thanks!

like image 356
jpfollenius Avatar asked Oct 30 '25 08:10

jpfollenius


1 Answers

That

MyClass.Rec.Member := 0;

doesn't compile is by design. The fact that the both "with"-constructs ever compiled was (AFAICT) a mere oversight. So both are not "safe to use".

Two safe solution are:

  1. Assign MyClass.Rec to a temporary record which you manipulate and assign back to MyClass.Rec.
  2. Expose TMyClass.Rec.Member as a property on its own right.
like image 144
Uli Gerhardt Avatar answered Nov 01 '25 03:11

Uli Gerhardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!