So I'm reading about indexers and basically understands that if you have a class with an array in it, you can use an indexer to get and set values inside that array. But what if you have more than one array in your class?
for example:
class myClass
{
string[] myArray1 = {"joe","zac","lisa"}
string[] myArray2 = {"street1","street2","street3"}
}
and I want to have an indexer for both myArray1 and myArray2... how can i do that?
You can't, basically. Well, you could overload the index, making one take long
indexes and one take int
indexes for example, but that's very unlikely to be a good idea, and may cause serious irritation to those who come after you maintaining the code.
What's more likely to be useful is to expose normal properties instead, which wrap the array (and possibly only provide read-only access). You can use ReadOnlyCollection<T>
for this in some cases:
public class Foo
{
private readonly string[] names;
private readonly string[] addresses;
// Assuming you're using C# 6...
private readonly ReadOnlyCollection<string> Names { get; }
private readonly ReadOnlyCollection<string> Addresses { get; }
public Foo()
{
names = ...;
addresses = ...;
Names = new ReadOnlyCollection<string>(names);
Addresses = new ReadOnlyCollection<string>(addresses);
}
}
See more on this question at Stackoverflow