Arrays In C#

Array Types

Arrays can be divided into the following four categories.

  • Single-dimensional arrays
  • Multidimensional arrays or rectangular arrays
  • Jagged arrays
  • Mixed arrays.

Note

In this article I will only focus on signal-dimensional array.

What is array?

Array is collection of homogeneous elements, which means we only can store the same type of element. For example if I create array of integer type, I only can store integer value. Let us learn with the help of example.

Create array of integer type.

  1. int[] studentRollNumber = new int[5];  
  2. studentRollNumber[0] = 25;  
  3. studentRollNumber[1] = 26;  
  4. studentRollNumber[2] = 27;  
  5. studentRollNumber[3] = 28;  
  6. studentRollNumber[4] = 29;  

In the above example I created array of integer type and assigned capacity 5. It means I can only store 5 integer values. Array works on index based, and indexing starts with 0. First element keeps at index 0.

Create array of string type

  1. string[] studentName = new string[5];  
  2. studentName[0] = "Amit";  
  3. studentName[1] = "Deepak";  
  4. studentName[2] = "Rajesh";  
  5. studentName[3] = "Rinku";  
  6. studentName[4] = "Deep";  

Can we store non-homogeneous data in array?

Yes we can store no-homogeneous data in array by creating array of object type. Let us see with the help of an example.

  1. object[] studentDetails = new object[5];  
  2. studentDetails[0] = "Amit";  
  3. studentDetails[1] = 2;  
  4. studentDetails[3] = 'C';  
  5. studentDetails[4] = true;  

In the above example as we can see we can store any type of data in the object array. This the feature provided by .net platform . In the .net framework you use the object type when you want to store any type of data.

How to retrieve data from array?

We can use foreach and for loop to retrieve data from a array. Let us with the help of example.

Retrieving array data using foreach loop.

  1. int[] studentRollNumber = new int[5];  
  2. studentRollNumber[0] = 25;  
  3. studentRollNumber[1] = 26;  
  4. studentRollNumber[2] = 27;  
  5. studentRollNumber[3] = 28;  
  6. studentRollNumber[4] = 29;  
  7. foreach(int rollNumber in studentRollNumber)  
  8. {  
  9.     Console.WriteLine(rollNumber);  
  10. }  

Retrieving data using for loop.

  1. int[] studentRollNumber = new int[5];  
  2. studentRollNumber[0] = 25;  
  3. studentRollNumber[1] = 26;  
  4. studentRollNumber[2] = 27;  
  5. studentRollNumber[3] = 28;  
  6. studentRollNumber[4] = 29;  
  7. for (int rollNumber = 0; rollNumber < studentRollNumber.Length; rollNumber = rollNumber + 1) {  
  8.     Console.WriteLine(studentRollNumber[rollNumber]);  
  9. }