Reputation: 1914
I have an abstract parent class that encapsulates access to an array of MyObjects:
public abstract class MyObjectIterator
{
public MyObjectIterator(MyObject[] MyObjects) { //constructor }
public Vector2 [] Coords { //A Get Function }
public Model[] Params { //A Get Function }
//THIS ISN'T SAFE! CAN STILL CHANGE MEMBERS OF THE SET
public MyObject[] MyObjects{ get; protected set; }
}
A child class of this already implements a single index indexer for another purpose, so I cannot use it to return a MyObject.
However, as it is unsafe/bad practise to return the array, as this means the elements within can be modified, I am looking for a way that I can provide a tidy interface to accessing a single element, e.g.
MyObject = Child.MyObjects[i];
but without providing set
access to any element of MyObjects.
A related question I have is: If I have an indexer on a parent class, can this be used when you have an object of a child class?
Edit:
I have decided to go with the method
public MyObject MyObject(int index) { return MyObjects[index]; }
As it most accomplishes what I was wanting.
Upvotes: 1
Views: 1022
Reputation: 1035
There is a ReadOnlyCollection class that may accomplish what you are looking for. This acts as a wrapper around the array. Use something like ReadOnlyCollection<MyObject> Data { get { return array.AsReadOnly(); } }
Mutating the underlying array will affect the ReadOnlyCollection. The collection itself is relatively lightweight, so you could create a new one each time the property is accessed or use caching if the property is accessed frequently (either at call site or within the class itself).
As for your second question, the answer is yes. Indexers in C# are rather like properties. If a property could be inherited (or required, such as due to an interface) an indexer would be as well.
Upvotes: 3