C # indexed property?

Several languages, such as Delphi, have a very convenient way to create indexers: not only the entire class, but even individual properties can be indexed, for example:

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 easily used:

 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 #?

+2
c # indexed-properties
Apr 15 '14 at 10:45
source share
1 answer

A famous solution is to create a proxy class:

 public class MyClass { public class MyPropProxy { private MyClass c; // ctor etc. public string this[int index] { get { return c.list[index]; } set { c.list[index] = value; } } } private List<string> list; private MyPropProxy myPropProxy; // ctor etc. public MyPropProxy MyProp { get { return myPropProxy; } } } 

But (except that it actually solves the problem), this solution introduces basically only the minuses:

  • This leads to code pollution (possibly) by a large number of small proxy classes.
  • The presented solution breaks encapsulation a bit (the inner class refers to the private members of the outer class), the better it will be to pass an instance of the MyPropProxy ctor list, which will require even more code.
  • Providing inner helper classes is not something I would suggest. This can be solved by adding an additional interface, but another object for implementation (testing, support, etc.).
However, there is another way. It also pollutes the code a bit, but certainly much less than the previous one:
 public interface IMyProp { string this[int index] { get; } } public class MyClass : IMyProp { private List<string> list; string IMyProp.this[int index] { get { return list[index]; } set { list[index] = value; } } // ctor etc. public IMyProp MyProp { get { return this; } } } 

Pros:

  • No proxy classes (occupying memory space, serve only one purpose and (in the simplest solution) interrupt encapsulation.
  • A simple solution, requires a little code to add another indexed property

Minuses:

  • Each property requires a different public interface.
  • As indexed properties increase, the class implements more and more interfaces.

This is the easiest (in terms of code length and complexity) way of introducing indexed properties in C #. Of course, if someone else does not become shorter and simpler.

+7
Apr 15 '14 at 10:45
source share
— -



All Articles