What & ldquo; type of & rdquo; statement in Delphi and how it can be used

advertisements

There is some strange code in Datasnap.DSReflect unit

  TDSAdapterClassType = type of TDSAdapterClass;

  TDSAdapterClass = class(TPersistent)
  private
    FAdapteeInstance: TObject;
  public
    constructor Create(AdapteeInstance: TObject); virtual;
  end;

and then it is used like this

var
  AdapteeInstance: TObject;
  FClassRef: TPersistentClass;

  Result := TDSAdapterClassType(FClassRef).Create(AdapteeInstance);

At first sight it seems just like another way of declaring class reference. But logic implies that it makes no sense to introduce such variation of language construct without adding more functionality to it. Following that logic I discovered that following declarations compile:

type
  TypeOfInteger = type of Integer;
  TypeOfByte = type of Byte;

  TRec = record
    x: integer;
  end;
  TypeOfTRec = type of TRec;

  TBytes = array of byte;
  TypeOfTBytes = type of TBytes;

Interesting enough, following declaration cannot be compiled.

type
  TypeOfString = type of String;

So the question is what type of actually represents and how can it be used in real life application, besides being some kind of alias for class of

Note: type of does not compile in Delphi 7, it seems that it is introduced later on, it is definitively there in XE, but I don't have Delphi 2007-2010 installed to try it there.

Update: I have filled bug report https://quality.embarcadero.com/browse/RSP-9850


It's not documented. The behaviour is non-repeatable. Some behaviour feels like class of but we don't need another way to do that. And class of for a value type is nonsensical.

My conclusion is that this must be a compiler bug. The code is invalid and should be rejected by the compiler. The bug is that the code is accepted instead of being rejected.

As can be seen from Hallvard Vassbotn's article, type of is a feature of the Delphi .net compiler that creates types that map to .net's System.RuntimeTypeHandle type. Loosely speaking therefore, type of provides for functionality equivalent to the C# typeof operator.

My best guess is that the Delphi desktop compiler accepts type of when it should not, as a vestige of the .net compiler.