C# Arrays


  • Array is a collection of the values of similar data type.
  • In C# array is a reference type.
  • Each array in C# is an object and inherited from the System.Array class.
  • The values present in an array are known as array elements. These elements can be accessed using the name of array and the index number representing the position of element in an array.
  • Array consists of the contiguous memory locations. Lower address memory location represents first element and highest address memory location represents last element.
  • csharp-array

Declaration of array


  • In C# we declare the array in the following way:
  • datatype[] arrayname;

  • Here datatype can be any primitive or refrence data type like int, float, string etc.
  • [] represents the size of the array.
  • arrayname is the name given to the array.

Here are some Examples of array declaration:


int[] length[5];
string name[3];
float area[2];

Creation of an array


  • Declaration of an array is not sufficient you have to create the array for using the array in the program. For creating an array you have to use the new keyword.
  • The basic syntax for creation of an array is given below:
  • datatype[] arrayname = new datatype[size];

  • Size here represents the size of an array.

Here are some Examples of creation of an array


int [] length= new int[5];
float[] area=new float[4];
char[] alphabet=new char[3];

Assigning value to the elements of array:


  • You have to assign values to the elements of an array before using them into the program.
  • You can assign the value to an array element by using its index number as given below:
  • string[] days =new string[7];
    days[0]="Monday";

  • You can also assign the value to the elements of array at the time of declaration or creation as the Examples given below:
  • int[] values=new int[3] {1,2,3};//at creation time
    float area={2.45,56.88};//at declaration time
    int length=new int[]{10,20,30);//without giving size

Accessing element stored in Array


  • You can access elements of array by writing the name of array with the index of the element in the square bracket which you want to access.
  • It should be known that in C# the index value is started from 0.
  • For Example to access the value stored in the first element of the days array, you can write the code as:
  • string[] days=new string[7]{"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
    string todays;
    today=days[0];

So in the above Example "Monday" will be stored in the string type variable 'today'.


Here is an Example which is sufficient to understand the concept of Array:


Example

using System;
namespace arrayprogram
{
class arrayexample
{
static void Main()
{
int[] arr;//declaration of array
arr=new int[5]{1,2,3,4,5};//creation and initialization of array
for(int i=0;i<5;i++)
{
Console.WriteLine("\nElement {0} of array = {1}",i+1,arr[i]);//accessing the array elements
}
Console.ReadLine();
}
}
}

The output of the above program would be as follows


Output

Element 1 of array = 1
Element 2 of array = 2
Element 3 of array = 3
Element 4 of array =4
Element 5 of array = 5

Types of array in C#


There are various types of arrays present in C#,which are given in the table given below:


csharp-array

One Dimensional array


  • An array which contains only one dimension is known as one dimensional array.
  • We declare a one dimensional array as datatype[] arrayname.
  • It is the simplest form of array which we have already discussed.

Multidimensional array


  • An array which contains more than one dimension is known as Multidimensional array. The simplest form of the multi dimensional array is two-dimensional array.
  • You can declare a multidimensional array as follows:
  • datatype[,] arrayname;//two-dimensional array
    datatype[,,]arrayname;//three-dimensional array

    For Example:

    int[,] lengthmatris;// two dimensional array
    string[,,] stringcube;//three dimensional array

  • Here we are going to discuss about the most common form of multidimensional array that is two-dimensional array.

Two-dimensional array


  • Two- dimensional array is a simplest form of the multidimensional array. An array having two dimensions is known as two-dimensional array.
  • Two-dimensional array can be considers as a matrix. A matrix has rows and columns as its dimension. If a two-dimensional array has size m by n then there are (m*n) elements in that array. Here is a Two-dimensional array of size (3*4) means a matrix of 3 rows and 4 columns so its element can be represented as:
  • csharp-array

Every element in two dimensional array is represent in the form of arrayname[x][y]. Here x and y shows the value of row and column respectively.


Initialization of two-dimensional array


  • We can initialize a two-dimensional array in the same way as one dimensional array.
  • Here is an Example of initialization of array:
  • int [,] matrix=
    {
    {1,2,3,4},//row1 values
    {5,6,7,8}//row2 values
    };
    //It is matrix of 2 rows and 4 columns

    Accessing the element of two dimensional array


    • You can access the elements of the two-dimensional array by using the array name with its index numbers.
    • For Example to accessing the elements stored in (2*4) matrix array in above Example you have to follows the give syntax:
    • matrix[0, 0]
      matrix[0, 1]
      matrix[0, 2]
      matrix[0, 3]
      matrix[1,0]
      matrix[1, 1]
      matrix[1, 2]
      matrix[1, 3]

    • Here is an Example which is sufficient to understand the concept of two-dimensional array:
    • Example

      using System;
      namespace arrayprogram
      {
      class twodimensionalarray
      {
      static void Main()
      {
      int[,]matrix=new int[2,4]{{1,2,3,4},{5,6,7,8}};//initialization of two dimensional array
      int i, j;
      for(i=0;i<2;i++)
      {
      for (j = 0;j < 4;j++)
      {
      Console.WriteLine("\nmatrix[{0},{1}]={2}",i,j,matrix[i,j]);//accessing the two-dimensional array elements
      }
      }
      Console.ReadLine();
      }
      }
      }

    The output of the above program would be:


    Output

    matrix[0,0] =1
    matrix[0,1] =2
    matrix[0,2] =3
    matrix[0,3] =4
    matrix[1,0] =5
    matrix[1,1]=6
    matrix[1,2] =7
    matrix[1,3] =8

    Jagged Array


    • In C# we have array of array, which is called jagged array.
    • Jagged array is an array of array in which each row of jagged array contains its own array and the length of each array can be different.
    • Here is an Example of declaration of jagged array:
    • int[][] jaggedArray;
      jaggedArray = new int[2][];
      jaggedArray[0] = new int[5];
      jaggedArray[1] = new int[3];

    Initialization of a jagged array


    • Before using the jagged array in the program we have to initialize the jagged array. We can initialize it at the time of declaration.
    • Here is an Example of initialization of a jagged array:
    • int[][] JaggedArray = new int[3][]
      {
      new int[] {5, 7, 2},
      new int[] {10, 20, 40},
      new int[] {3, 25},
      };

      Accessing the element of jagged array


      • You can access the element of a jagged array with the help of array name and its index.
      • For Example:

        Jaggedarray[i][j];

      • Here is an Example which is sufficient to understand the concept of jagged array:
      • Example

        using System;
        namespace arrayprogram
        {
        class jaggedarrayExample {
        static void Main()
        {
        int[][] JaggedArray = new int[3][]{ new int[] {5, 7}, new int[] {10, 20}, new int[] {3, 25} };//initialization jagged array
        int i, j;
        for(i=0;i<3;i++)
        {
        for (j = 0; j < 2; j++)
        {
        Console.WriteLine("\nJaggedArray[{0}][{1}]={2}",i,j,JaggedArray[i][j]);//accessing the jaggedarray elements
        }
        }
        Console.ReadLine();
        }
        }
        }

      The output of the above program is given below:


      Output

      :
      JaggedArray[0][0]=5
      JaggedArray[0][1]=7
      JaggedArray[1][0]=10
      JaggedArray[1][1]=20
      JaggedArray[2][0]=3
      JaggedArray[2][1]=25

      Param Array


      • Sometime on dealing with the method you are not sure about the number of parameters so in that case Param array is used.
      • Param array is used to passing unknown number of parameter to a method.
      • Here is an Example of a Param Array:
      • Example

        using System;
        namespace arrayprogram
        {
        class Paramarray
        {
        static int mul(params int[] numbers)
        {
        int mul1 = 1;
        foreach (int n in numbers)
        {
        mul1 = mul1* n;
        }
        return mul1;
        }
        static void Main(string[] args)
        {
        int mul1;
        // passing three parameters
        mul1 = Paramarray.mul(1, 2, 3);
        Console.WriteLine("multiplication of 1,2,3 is:{0}", mul1);
        // passing six parameters
        mul1 = Paramarray.mul(1,2,3,4,5,6);
        Console.WriteLine("multiplication of 1,2,3,4,5,6 is:{0}", mul1);
        Console.ReadLine();
        }
        }
        }

      In the above Example first time we are passing 3 parameters to method mul for multiplication and in the second time we are passing the 6 parameters to method mul for multiplication. Which justify that we can pass any number of parameter to a method by using param array.


      So we get the following output for the above program:


      Output

      multiplication of 1,2,3 is:6
      multiplication of 1,2,3,4,5,6 is:720

      More about array


      In this section we will study some more concepts related to the C# array like:


      • Passing array as parameter.
      • Array Class and Array Functions

      Let us discuss the both of the above concepts in detail:


      Passing array as parameter


      • We can also pass an array to a method as parameter in C#.
      • Here is an Example in which an array of elements 5 is passed to the method which add the elements of array for getting their sum:
      • Example

        using System;
        namespace arrayprogram
        {
        class Passingarray
        {
        static void addarrayelement(int[] addarray)
        {
        int i,sum=0;
        for(i=0;i<5;i++)
        {
        sum=sum+addarray[i];
        }
        Console.WriteLine("sum of elements of array is:{0}",sum);
        }
        static void Main(string[] args)i=0;
        {
        int[] number = new int[5] { 1, 2, 3, 4, 5 };i=0;
        Passingarray.addarrayelement(number);//Passing an array as parameteri=0;
        Console.ReadLine();
        }
        }
        }

      The output of the above program is:


      Output

      sum of element of array is:15

      Array Class and Array Functions


      • In C# all arrays are treated as object and inherited from the Array class. This Array class is defined in the System namespace.
      • Following table contains the various properties of the Array class:
      • csharp-array
      • Here is an Example which shows the use of properties of array class:
      • Example

        namespace arrayclassi=0;
        {
        class arrayclasspropertiesi=0;
        {
        static void Main(string[] args)i=0;
        {
        int[] number = new int[5] { 1, 2, 3, 4, 5 };i=0;
        int length, rank;
        long longlength;
        bool fixedsize, readonly1;
        length=number.Length;
        Console.WriteLine("Length of array is:{0}", length);
        longlength = number.LongLength;
        Console.WriteLine("LongLength of array is:{0}", longlength);
        rank = number.Rank;
        Console.WriteLine("Rank of array is:{0}", rank);
        fixedsize = number.IsFixedSize;
        Console.WriteLine("Array has fixed size:{0}", fixedsize);
        readonly1 = number.IsReadOnly;
        Console.WriteLine("Array is readonly:{0}", readonly1);
        Console.ReadLine();
        }
        }
        }

      The output the above program will be:


      Output

      Length of array is:5
      LongLength of array is:5
      Rank of array is:1
      Array has fixed size:True
      Array is readonly:False

      Functions of Array Class


      Some most commonly used functions of an array class are given below in the table:


      csharp-array
      Example

      Here is an Example of which shows the use of function of array class:


      using System;
      namespace arrayclass
      {
      class arrayclassproperties
      {
      static void Main(string[] args)
      {
      int[] number = new int[5] {
      5,2,3,1,6};
      int[] number1 = new int[5];
      int i;
      int length, lowerbound,upperbound;
      Console.WriteLine("Orignal array:");
      for( i=0;i<5;i++)
      {
      Console.WriteLine(""+number[i]);
      }
      Console.WriteLine("Sorted array:");
      Array.Sort(number);//Sorting of array.
      for (i = 0;
      i < 5;
      i++)
      {
      Console.WriteLine("" + number[i]);
      }
      Console.WriteLine("Reverse array:");
      Array.Reverse(number);
      //Reverse array
      for (i = 0;
      i < 5;
      i++)
      {
      Console.WriteLine("" + number[i]);
      }
      length = number.GetLength(0);
      //returning length from specific position
      Console.WriteLine("Length of array is:{0}", length);
      lowerbound = number.GetLowerBound(0);
      Console.WriteLine("Lower bound of the array is:{0}",lowerbound);
      upperbound = number.GetUpperBound(0);
      Console.WriteLine("Upper bound of the array is:{0}", upperbound);
      Array.Copy(number,number1,5);
      //copying item of array number to array number1
      Console.WriteLine("Elemenet of copied array are:");
      for (i = 0;
      i < 5;
      i++)
      {
      Console.WriteLine("" + number1[i]);
      }
      Array.Clear(number, 0, 5);
      //Removing items from array.
      Console.WriteLine("Array after removing the elements");
      for (i = 0;
      i < 5;
      i++)
      {
      Console.WriteLine("" + number[i]);
      }
      Console.ReadLine();
      }
      }
      }

      The output of the above program will be as follows:


      Output

      Orignal array:
      5
      2
      3
      1
      6
      Sorted array:
      1
      2
      3
      5
      6
      Reverse array:
      6
      5
      3
      2
      1
      Length of array is:5
      Lower bound of the array is:0
      Upper bound of the array is:4
      Element of copied array are:
      6
      5
      3
      2
      1
      Array after removing the element
      0
      0
      0
      0
      0