R – Delphi: Records in Classes

delphidelphi-2007delphi-2010records

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!

Best Solution

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.