A famous solution is to create a proxy class:
public class MyClass { public class MyPropProxy { private MyClass c;
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; } }
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.
Spook Apr 15 '14 at 10:45 2014-04-15 10:45
source share