C# - Arrays



An array stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type stored at contiguous memory locations.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

Arrays in C#

Declaring a C# Array

You can declare an array in C# by specifying the data type followed by square brackets and array name.

Syntax

Following is the syntax of an array declaration in c# −

datatype[] arrayName;

Where,

  • datatype is used to specify the type of elements in the array.
  • [ ] specifies the rank of the array. The rank specifies the size of the array.
  • arrayName specifies the name of the array.

For example:

double[] balance;

Initializing an Array

Declaring an array does not allocate memory for its elements. When the array variable is initialized, you can assign values to it.

An array is a reference type in C#, so you need to use the new keyword to allocate memory for its elements.

Syntax

The following is the syntax to initialize an array −

double[] balance = new double[10];

Assigning Values to an Array

You can assign values to individual array elements using their index number, as shown below −

double[] balance = new double[10];
balance[0] = 4500.0;

You can also assign values to an array at the time of declaration, as shown below −

double[] balance = { 2340.0, 4523.69, 3421.0 };

You can create and initialize an array using the new keyword, as shown below −

int[] marks = new int[5] { 99, 98, 92, 97, 95 };

You may also omit the size of the array when using an initializer list, as shown below −

int[] marks = new int[] { 99, 98, 92, 97, 95 };

You can copy an array variable into another target array variable. In this case, both the target and source will point to the same memory location −

int[] marks = new int[] { 99, 98, 92, 97, 95 };
int[] score = marks;

When you create an array, C# compiler implicitly initializes each array element to a default value depending on the array type. For example, for an int array all elements are initialized to 0.

Accessing Array Elements

You can access array elements using an index within square brackets after the array name. Array indices start from 0, meaning the first element is at index 0, the second at 1, and so on.

Here's an example of accessing an array element:

double salary = balance[9];

Example: Using for Loop

The following example demonstrates how to declare, assign, and access array elements in C#:

using System;
namespace ArrayApplication {
   class MyArray {
      static void Main(string[] args) {
         int[] n = new int[10]; // n is an array of 10 integers

         // Initializing elements of array n
         for (int i = 0; i < 10; i++) {
            n[i] = i + 100;
         }
         
         // Accessing and displaying array elements
         for (int j = 0; j < 10; j++) {
            Console.WriteLine("Element[{0}] = {1}", j, n[j]);
         }
         Console.ReadKey();
      }
   }
}

When executed, this program outputs:

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

Example: Using foreach Loop

You can also iterate through an array using the foreach loop.

using System;
namespace ArrayApplication {
   class MyArray {
      static void Main(string[] args) {
         int[] n = new int[10]; // n is an array of 10 integers

         // Initializing elements of array n
         for (int i = 0; i < 10; i++) {
            n[i] = i + 100;
         }
         
         // Using foreach loop to access array elements
         int index = 0;
         foreach (int value in n) {
            Console.WriteLine("Element[{0}] = {1}", index, value);
            index++;
         }
         Console.ReadKey();
      }
   }
}

When executed, this program outputs:

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107

Finding the Length of an Array

You can find the total number of elements in an array using the Length property. This property returns the total count of elements in an array.

Here is a simple example of how to get the length of an array:

int[] numbers = { 10, 20, 30, 40, 50 };
int length = numbers.Length;
Console.WriteLine("Array Length: " + length);

Example

The following example demonstrates how to declare an array and find its length in C#:

using System;
namespace ArrayApplication {
   class ArrayLength {
      static void Main(string[] args) {
         int[] numbers = { 10, 20, 30, 40, 50 };
         // Finding length of the array
         Console.WriteLine("The total number of elements in the array: " + numbers.Length);

         Console.ReadKey();
      }
   }
}

When executed, this program outputs:

The total number of elements in the array: 5

Sorting an Array

You can sort an array in C# using the Array.Sort() method, which sorts the array elements in ascending order.

Example

The following example demonstrates how to sort an array in C#:

using System;
namespace ArrayApplication {
   class SortArray {
      static void Main(string[] args) {
         int[] numbers = { 50, 20, 40, 10, 30 };

         // Sorting the array in ascending order
         Array.Sort(numbers);

         Console.WriteLine("Sorted Array:");
         foreach (int num in numbers) {
            Console.Write(num + " ");
         }

         Console.ReadKey();
      }
   }
}

When executed, this program outputs:

Sorted Array:
10 20 30 40 50

Sorting Array Elements in Descending Order

You can sort an array in descending order by using the Array.Sort() followed by Array.Reverse(), as shown below:

Syntax

Following is the syntax to sort an array in descending order −

Array.Sort(arrayName);
Array.Reverse(arrayName);

Example

The following example demonstrates how to sort an array in descending order in C#:

using System;
namespace ArrayApplication {
   class SortArray {
      static void Main(string[] args) {
         int[] numbers = { 50, 20, 40, 10, 30 };

         // Sorting the array in descending order
         Array.Sort(numbers);
         Array.Reverse(numbers);

         Console.WriteLine("Sorted Array in Descending Order:");
         foreach (int num in numbers) {
            Console.Write(num + " ");
         }

         Console.ReadKey();
      }
   }
}

When executed, this program outputs:

Sorted Array in Descending Order:
50 40 30 20 10

Copying an Array

You can copy an array to another array using the Array.Copy() or Array.Clone() method.

Syntax

Following is the syntax to copy an array:

Array.Copy(sourceArray, destinationArray, length);

Using Clone() to create a shallow copy:

destinationArray = sourceArray.Clone() as int[];

Example: Copying an Array

The following example demonstrates how to copy an array in C#:

using System;
namespace ArrayApplication {
   class CopyArray {
      static void Main(string[] args) {
         int[] sourceArray = { 1, 2, 3, 4, 5 };
         int[] destinationArray = new int[sourceArray.Length];

         // Copying array using Array.Copy()
         Array.Copy(sourceArray, destinationArray, sourceArray.Length);

         Console.WriteLine("Copied Array:");
         foreach (int num in destinationArray) {
            Console.Write(num + " ");
         }

         Console.ReadKey();
      }
   }
}

When executed, this program outputs:

Copied Array:
1 2 3 4 5

Using Clone() to Copy an Array

The Clone() method creates a shallow copy of the array. Consider the following example −

using System;
namespace ArrayApplication {
   class CloneArray {
      static void Main(string[] args) {
         int[] sourceArray = { 10, 20, 30, 40, 50 };

         // Cloning the array
         int[] clonedArray = (int[])sourceArray.Clone();

         Console.WriteLine("Cloned Array:");
         foreach (int num in clonedArray) {
            Console.Write(num + " ");
         }

         Console.ReadKey();
      }
   }
}

When executed, this program outputs:

Cloned Array:
10 20 30 40 50

More on C# Arrays

There are following few important concepts related to array which should be clear to a C# programmer −

Sr.No. Concept & Description
1 Multi-dimensional arrays

C# supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array.

2 Jagged arrays

C# supports multidimensional arrays, which are arrays of arrays.

3 Passing arrays to functions

You can pass to the function a pointer to an array by specifying the array's name without an index.

4 Param arrays

This is used for passing unknown number of parameters to a function.

5 The Array Class

Defined in System namespace, it is the base class to all arrays, and provides various properties and methods for working with arrays.

Array Properties and Methods

You can explore all Array properties and methods here: C# Array Class Properties and Methods

Advertisements