How to access elements from multi-dimensional array in C#?


To acess element from the multi-dimensional array, just add the index for the element you want, for example −

a[2,1]

The above access element from 3rd row and 2nd column ie element 3 as shown below in out [3,4] array −

0 0
1 2
2 4
3 6

Let us see whatever we discussed and access element from a 2 dimensional array −

Example

using System;

namespace Program {
   class Demo {
      static void Main(string[] args) {

         int[,] a = new int[4, 2] {{0,0}, {1,2}, {2,4}, {3,6} };
         int i, j;

         for (i = 0; i < 4; i++) {
   
            for (j = 0; j < 2; j++) {
               Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
            }

         }

         // accessing element
         Console.WriteLine(a[2,1]);

         Console.ReadKey();
      }
   }
}

Updated on: 21-Jun-2020

229 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements