Array-csharp

Last modified on May 08th, 2020 by DigitalIndiaInfo Team.


C# Arrays

Updated on:

A variable is used to store a literal value, whereas an array is used to store multiple literal values.

An array is the data structure that stores a fixed number of literal values (elements) of the same data type. Array elements are stored contiguously in the memory.

In C#, an array can be of three types: single-dimensional, multidimensional, and jagged array. Here you will learn about the single-dimensional array.

The following figure illustrates an array representation.

Array Representation

Array Declaration and Initialization

An array can be declared using by specifying the type of its elements with square brackets.

Example: Array Declaration
int[] evenNums;  // integer array
string[] cities; // string array

The following declares and adds values into an array in a single statement.

Example: Array Declaration & Initialization
int[] evenNums = new int[5]{ 2, 4, 6, 8, 10 }; 
string[] cities = new string[3]{ "Mumbai", "London", "New York" };

Above, evenNums array can store up to five integers. The number 5 in the square brackets new int[5] specifies the size of an array. In the same way, the size of cities array is three. Array elements are added in a comma-separated list inside curly braces { }.

Arrays type variables can be declared using var without square brackets.

Example: Array Declaration using var
var evenNums = new int[]{ 2, 4, 6, 8, 10}; 
var cities = new string[]{ "Mumbai", "London", "New York" }; 

If you are adding array elements at the time of declaration, then size is optional. The compiler will infer its size based on the number of elements inside curly braces, as shown below.

Example: Short Syntax of Array Declaration
int[] evenNums = { 2, 4, 6, 8, 10}; 
string[] cities = { "Mumbai", "London", "New York" }

The following example demonstrate invalid array declarations.

Example: Invalid Array Creation
//must specify the size 
int[] evenNums = new int[]; 
//number of elements must be equal to the specified size 
int[] evenNums = new int[5] { 2, 4 };
//cannot use var with array initializer
var evenNums = { 2, 4, 6, 8, 10}; 

Late Initialization

It is not necessary to declare and initialize an array in a single statement. You can first declare an array then initialize it later on using the new operator.

Example: Late Initialization
int[] evenNums;
evenNums = new int[5];
// or
evenNums = new int[]{ 2, 4, 6, 8, 10 };

Accessing Array Elements

Array elements can be accessed using an index. An index is a number associated with each array element, starting with index 0 and ending with array size - 1.

The following example add/update and retrieve array elements using indexes.

Example: Access Array Elements using Indexes
int[] evenNums = new int[5];
evenNums[0] = 2;
evenNums[1] = 4;
//evenNums[6] = 12;  //Throws run-time exception IndexOutOfRange
Console.WriteLine(evenNums[0]);  //prints 2
Console.WriteLine(evenNums[1]);  //prints 4

Note that trying to add more elements than its specified size will result in IndexOutOfRangeException.

Accessing Array using for Loop

Use the for loop to access array elements. Use the length property of an array in conditional expression of the for loop.

Example: Accessing Array Elements using for Loop
int[] evenNums = { 2, 4, 6, 8, 10 };
for(int i = 0; i < evenNums.Length; i++)
                        Console.WriteLine(evenNums[i]);  
for(int i = 0; i < evenNums.Length; i++)
    evenNums[i] = evenNums[i] + 10;  // update the value of each element by 10

Accessing Array using foreach Loop

Use foreach loop to read values of an array elements without using index.

Example: Accessing Array using foreach Loop
int[] evenNums = { 2, 4, 6, 8, 10}; 
string[] cities = { "Mumbai", "London", "New York" }; 
foreach(var item in evenNums)
                        Console.WriteLine(item);   
foreach(var city in cities)
                        Console.WriteLine(city);  

LINQ Methods

All the arrays in C# are derived from an abstract base class System.Array.

The Array class implements the IEnumerable interface, so you can LINQ extension methods such as Max(), Min(), Sum(), reverse(), etc. See the list of all extension methods here.

Example: LINQ Methods
int[] nums = new int[5]{ 10, 15, 16, 8, 6 };
nums.Max(); // returns 16
nums.Min(); // returns 6
nums.Sum(); // returns 55
nums.Average(); // returns 55

The System.Array class also includes methods for creating, manipulating, searching, and sorting arrays. See list of all Array methods here.

Example: Array Methods
int[] nums = new int[5]{ 10, 15, 16, 8, 6 };
Array.Sort(nums); // sorts array 
Array.Reverse(nums); // sorts array in descending order
Array.ForEach(nums, n => Console.WriteLine(n)); // iterates array
Array.BinarySearch(nums, 5);// binary search 

Passing Array as Argument

An array can be passed as an argument to a method parameter. Arrays are reference types, so the method can change the value of the array elements.

Example: Passing Array as Argument
public static void Main(){
                        int[] nums = { 1, 2, 3, 4, 5 };
    UpdateArray(nums); 
                        foreach(var item in nums)
                        Console.WriteLine(item);   
}
                    
public static void UpdateArray(int[] arr)
{
                        for(int i = 0; i < arr.Length; i++)
        arr[i] = arr[i] + 10;   
}

Learn about multidimensional and jagged array next.



References :

  • www.tutorial.digitalindiainfo.com