C# Multidimensional indexer

In this chapter you will learn:

  1. How to create C# multidimensional indexer
  2. How to create read only multidimensional indexer

Create Multidimensional indexer

We have use more than one index for an indexer.


using System;/*from  w  w w  .j a v  a2s. c  o  m*/
class TwoD
{
    int[,] matrix =
  {
    {0,1,2},
    {3,4,5},
    {6,7,8}
  };


    public int this[int i, int j]
    {
        get
        {
            return matrix[i, j];
        }
    }

}



class Program
{
    static void Main(string[] args)
    {
        TwoD t = new TwoD();
        Console.WriteLine(t[1, 1]);

    }
}

The output:

Read only multidimensional indexer


using System; /*  ww  w  . ja  v  a2  s.com*/
 
class MyArray2D {  
  public MyArray2D(int r, int c) { 
  } 
 
  // This is the indexer for MyArray2D. 
  public int this[int index1, int index2] { 
    // This is the get accessor. 
    get { 
        return index1 + index2; 
    } 
  } 
}  
  
class MainClass {  
  public static void Main() {  
    MyArray2D myArray = new MyArray2D(3, 5); 
    int x; 
 
    for(int i=0; i < 6; i++) { 
      x = myArray[i,i]; 
      if(x != -1) Console.Write(x + " "); 
    } 
    Console.WriteLine(); 
 
  } 
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to create overloaded indexer
Home »
  C# Tutorial »
    C# Types »
      C# Indexer
C# Indexer
C# String type indexer
C# Multidimensional indexer
C# Indexer overloading
C# Appendable Indexer
C# Indexer logic