C# - Arrays


An arrays are used to store multiple values of same data type in one variable. It is allows you to work with collections of variables.

Instead of declaring separate variables for each value we can use array. Arrays are fundamental data structures in C# and are extensively used in various applications for storing and manipulating collections of values.

Declaring and Initializing and Array

To declare an array we have to specify the variable type with square brackets. Lets define a simple array for string variable type.

string[] cars;

Now its time to store some values inside the array. Here we will use the same array for cars as we declared above. Let’s do it.

string[] cars = {"BMW", "Ford", "Nissan"};

To create an array of integer variable type, we could write:

string[] marks = {80,75,90,60};

Accessing Array Elements

We can access the array element using index number. Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

string[] cars={"BMW","Ford","Nissan"};
    Console.WriteLine(cars[0]);

Change Array Value

To change the array value, we have to specify index number.

string[] cars = {"BMW","Ford","Nissan"};
    Cars[0] = "updated value";
    Console.WriteLine(cars[0]);

Array Iteration

We can iterate through arrays using loops like for, foreach, or while. You can learn more about loops here

int[] numbers = { 1, 2, 3, 4, 5 }; 

    // Using a for loop 
    for (int i = 0; i < numbers.Length; i++) 
    { 
        Console.WriteLine(numbers[i]); 
    } 

    // Using foreach loop (for each element) 
    foreach (int num in numbers) 
    { 
        Console.WriteLine(num); 
    }