16

Is it possible to have two properties with the same name?

property  Cell [Cl, Rw: Integer]: string   read getCell  write setCell;
property  Cell [ColName: string; Rw: Integer]: string read getCellByCol write setCellByCol;

Well, I tried it and the compiler won't let me do it, but maybe there is a trick...?

Gabriel
  • 20,797
  • 27
  • 159
  • 293

1 Answers1

31

No - but then again: Yes... Sort of...

function    getP1(Cl,Rw : integer) : string;
procedure   setP1(C1,Rw : integer ; const s : string);
function    getP2(const Cl : string ; Rw : integer) : string;
procedure   setP2(const C1 : string ; Rw : integer ; const s : string);
property    P1[Cl,Rw : integer] : string read getP1 write setP1; default;
property    P1[const Cl : string ; Rw : integer] : string read getP2 write setP2; default;

The trick is to name the property the same, and to mark both with "default" clause. Then you can access the same property name with various parameters:

P1['k',1]:=P1[2,1];
P1[2,1]:=P1['k',1];

compiles fine.Don't know if this is offcially supported or if there's some other problems with it, but it compiles fine and calls the correct getter/setter (tested in Delphi 2010).

This of course only works if you don't already use a default property for your class, as the only way I have been able to make it work is via the default clause.

HeartWare
  • 7,464
  • 2
  • 26
  • 30
  • 1
    Yes this is officially supported. The default property allows you to access the class as an array. Overloading allows you to access the 'array' in different ways. Because the parameter types vary the compiler is able to disambigate the correct overload. ..... Of course why it's not allowed for non default array properties is a mystery to me. – Johan Sep 15 '15 at 13:33
  • Thank you hor the observation. It was really interesting to read your answer. How do you think, is it possible to use generics for this purpose then? I am currently thinking at `TDictionary`. – asd-tm Sep 15 '15 at 14:19
  • 4
    Upvoted, I've learned something new! http://docwiki.embarcadero.com/RADStudio/Seattle/en/Properties#Array_Properties *A class can have only one default property with a given signature (array parameter list), but it is possible to overload the default property. Changing or hiding the default property in descendent classes may lead to unexpected behavior, since the compiler always binds to properties statically.* – fantaghirocco Sep 15 '15 at 14:20