A few languages - like Delphi - has a very convenient way of creating indexers: not only the whole class, but even single properties can be indexed, for instance:
type TMyClass = class(TObject)
protected
function GetMyProp(index : integer) : string;
procedure SetMyProp(index : integer; value : string);
public
property MyProp[index : integer] : string read GetMyProp write SetMyProp;
end;
This can be used easily:
var c : TMyClass;
begin
c = TMyClass.Create;
c.MyProp[5] := 'Ala ma kota';
c.Free;
end;
Is there a way to achieve the same effect in C# easily?
The well-known solution is to create a proxy class:
But (with exception, that this actually solves the problem), this solution introduces mostly only cons:
MyPropProxy's ctor, what would require even more code.There's another way, though. It also pollutes the code a little, but surely a lot less, than the previous one:
Pros:
Cons:
This is the simplest (in terms of code length and complexity) way of introducing indexed properties to C#. Unless someone posts even shorter and simpler one, of course.