Home > Software design >  Indexer working with both normal and jagged arrays
Indexer working with both normal and jagged arrays

Time:07-06

I have two classes:

//The class with the Main method
    Six ujhb = new(4);
//fill in all the arrays but not the inner arrays
    for(int i = 0; i < ujhb.Size; i  ) {
        ujhb[i] = new int[i 1];
        Console.WriteLine(ujhb[i]);
    }
//get a value of a specific inner array
    Console.WriteLine(ujhb[2][0]);

class Six {

    int[][] a;
    public int Size;

    public Six(int v) {
        a = new int[v][];
        Size = v;
    }

    public int[] this[int index] {
        get {
            return a[index];
        }

        set {
            a[index] = value;
        }
    }
}

So I have an Indexer which gets an array or sets an array.
I just don'tunderstand how does this line work:

Console.WriteLine(ujhb[2][0]);

Considering that the indexer is told to return int[ ] s not int[ ][ ] s?

CodePudding user response:

It's two operations.

1.) ujhb[2] first calls the indexer with index == 2, which returns an array (int[]).

2.) Then [0] accesses the item at index 0 in that array.

Basically, it's short for:

var array = ujhb[2]; // indexer call
var item = array[0]; // array access
Console.WriteLine(item);
  •  Tags:  
  • c#
  • Related