Arrays in C#

In general when we store values we use a variable but the problem comes is when we want to store multiple values within one variable and using what we learned it isn't possible to store multiple values within a single variable, that's why we will be learning about Arrays because it will be helping us to store multiple values within a single variable and a array can be of any type be it integer, string or char it can be of any type.

There are 2 ways to declare an array:

Way 1: int[] val = {1, 2, 3, 4};

OR

Way 2: int[] val = new int [4] {1, 2, 3, 4};

The difference between both the ways is that Way 1 is dynamic and Way 2 is static means in a static array the size of the array is already defined in the memory and because of that we can't add more values to the array.

Accessing values in array

We are already familiar with the concept of indexing and that's what is going to help us access values within an array.

int[] val = {1, 2, 3, 4};
Console.WriteLine(val[2]);

Array Methods

C# comes with a number of useful properties and methods that we can use with an array and we will be exploring some of them.

Length:

This method helps us to get the length of a certain array.

int[] val = {1, 2, 3, 4};
Console.WriteLine(val.Length);

Sort:

This method helps us to sort an array in ascending order, it takes an array as an argument.

int[] val = {9, 3, 8, 2, 5};
Array.Sort(val);

IndexOf:

The method returns the index of the first value found.

int[] val = {9, 3, 8, 2, 5};
int idx = Array.IndexOf(val, 2);
Console.WriteLine(idx);

Max, Min, Sum

These functions can be found within System.Linq namespace, Max returns the largest value available within an array, Min return the lowest one and sum returns the total summation of all the elements in the array.

int[] val = {9, 3, 8, 2, 5};

Console.WriteLine(val.Max());
Console.WriteLine(val.Min());
Console.WriteLine(val.Sum());