Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi property getter function using generics

It would be nice to have generic property getters/setters to perform a common task on each access.

That code gives a compile-time error in Delphi XE2 'E2008 Incompatible types'. A similar code gave an internal error during compilation, but never compiles. Do I make a mistake or it is a compiler limitation?

type TFoo = class
private
  function Get<T>: T;
public
  property Bar: Integer read Get<Integer>;
end;

function TFoo.Get<T>: T;
begin
  Result := 0;
end;
like image 496
malom Avatar asked Feb 15 '26 12:02

malom


1 Answers

The following things can be generic in the Delphi language:

  • classes, e.g. TFooClass<T> = class
  • records, e.g. TFooRecord<T> = record
  • interfaces, e.g. TFooInterface<T> = interface
  • procedural types, e.g. TFooProc<T> = procedure
  • methods, e.g. procedure FooMethod<T>()

Properties cannot be generic themselves, and cannot be implemented using generic getter or setter methods.

like image 122
David Heffernan Avatar answered Feb 18 '26 06:02

David Heffernan



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!