How do you use indexers with array of objects?

401 views Asked by At

How can we use indexers if we are using array of objects???

For a single object:

static void Main(string[] args)
{
    MYInd mi = new MYInd();
    mi[1] = 10;
    Console.WriteLine(mi[1]);
    mi[2, 10] = 100;
    Console.WriteLine(mi[2]);

    Console.WriteLine(mi[3, 10]);

What should be done for array of objects?

MYInd[] mir = new MYInd[3];

How can we use each object and the indexer?

2

There are 2 answers

2
Albin Sunnanbo On BEST ANSWER

You have a couple of options, if you want to iterate you do

foreach(MYInd mi in mir)
    Console.WriteLine(mi[3, 10]);

If you want to pick out a specific MYInd from the array you can do it in one step

Console.WriteLine(mir[1][3, 10]); // [1] picks out one object from the array

or in two steps

MYInd mi = mir[1]; // pick out one object from the array
Console.WriteLine(mi[3, 10]);
2
xanatos On
mir[0][1, 2]

But you can imagine it as:

(mir[0])[1, 2]

The brackets aren't necessary because the [ operator is parsed left to right (like (1 + 2) + 3 == 1 + 2 + 3. I think it's called left-associativity, but I'm not sure sure :-) )

Remember that you have to initialize BOTH the array and the elements:

var mir = new MyInd[5];
for (int i = 0; i < mir.Length; i++) 
{
    mir[i] = new MyInd();
}