Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Indexer working with both normal and jagged arrays

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading