How to create C# multidimensional indexer

Create Multidimensional indexer

We have use more than one index for an indexer.


using System;//from  w w w. ja v a2 s  .  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; /* w ww. ja v a 2 s  .c om*/
 
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.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor