An array is a sequential collection of variables of the same data type. Arrays having more than one dimension is known as a multidimensional array. An array with a single dimension (single row) is known as a single dimensional array.

Syntax and array decleration

An array can be declared by specifying its type name followed by square brackets ([]).

//A two dimensional array
int[,] ArrayName;
//Three dimensional array
char[,,] ArrayName;
  • Datatype is the type of the elements of the array.
  • Size of the array can be specified in the [].
  • ArrayName is the name of the array.

Array initialization

int[,] IntArray = new int[2, 3]
{
{1, 2, 3},
{3, 4, 5}
};
//Or
int[,] IntArray1 = new int[,]
{
{1, 2, 3},
{3, 4, 5}
};

Assigning values

The value of any array element can be changed using its index.

int[,] IntArray = new int[2, 3]
{
{1, 2, 3},
{3, 4, 5}
};
IntArray[1, 0] = 10;
IntArray[1, 1] = 11;
IntArray[1, 2] = 12;

Accessing array elements

Array elements can be accessed using any of the below mentioned methods:

Using index:

using System;   //Adding namespaces
namespace LearnCSharp //Namespace of the class
{
class Program //The class
{
static void Main(string[] args) //Main method
{
int[,] IntArray = new int[2, 3]
{
{1, 2, 3},
{3, 4, 5}
};
Console.WriteLine("{0} {1} {2}", IntArray[0, 0], IntArray[0, 1], IntArray[0, 2]);
Console.WriteLine("{0} {1} {2}", IntArray[1, 0], IntArray[1, 1], IntArray[1, 2]);
Console.ReadKey();
}
}
}

Output

1 2 3
3 4 5

Using for loop:

using System;   //Adding namespaces
namespace LearnCSharp //Namespace of the class
{
class Program //The class
{
static void Main(string[] args) //Main method
{
int[,] IntArray = new int[2, 3]
{
{1, 2, 3},
{3, 4, 5}
};
//Row count
int rows = IntArray.GetLength(0);
//Column count
int column = IntArray.GetLength(1);
for(int i=0; i<rows; i++)
{
Console.WriteLine("Row {0}:", i);
for(int j=0; j<column; j++)
{
Console.Write("{0} ", IntArray[i, j]);
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}

Output

Row 0:1 2 3Row 1:3 4 5