C# Arrays With Examples – Programming, Pseudocode Example, C# Programming Example
Arrays C# Console

C# Arrays With Examples

How to Declare Array in C#

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.

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

Declaring Arrays

To declare an array in C#, you can use the following syntax .

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.

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.

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.

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.

Accessing Array using foreach Loop

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

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. 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.