8
votes

I'm trying to write a property which uses generics:

type TMyClass = class
  protected
    function GetCountBy<T: Class>: Integer;
  public
    property CountBy<T: Class>: Integer read GetCountBy<T>;
  end;

but the compile fails on the property declaration with the message 'Property CountBy does not exist in base class', and the red squiggle on the opening < of the property name.

Is there any way to achieve this?

Edit: Here's my other use case, which is more complex but more real world:

property ItemsBy<T: Class>[Index: Integer]: T read GetItemsBy<T> write SetItemsBy<T>;

The function filters the contents of a list to return the Index'th item of the specified class.

2
You simply need TDictionary<TClass, Integer> here. Generics are not appropriate to this problem. - David Heffernan
-1. This would be a better question if it were motivated by a problem that would actually benefit from generics. The example "generic property" in the question doesn't need generics at all. This has the potential to be a fine question asking about the right syntax for generic properties (if such syntax even exists), but the example problem to be solved by such syntax doesn't really demonstrate the need. - Rob Kennedy

2 Answers

10
votes

Generic properties are not supported in Delphi. Only generic classes, or generic methods.

I can't find anything in the documentation that explicitly states that limitation. On the other hand the documentation only describes generic classes and generic methods. And the new language grammar to support generics also makes no mention of properties.

1
votes

I'm not up to speed on generics but shouldn't the declaration be more like this

  type TMyClass<T: class> = class
  protected
    function GetCountBy<T>: Integer;
  public
    property CountBy<T>: Integer read GetCountBy<T>;
  end;