Ar

Arrays in C#

29 exercises

About Arrays

Data structures that can hold zero or more elements are known as collections. An array is a collection that has a fixed size/length and whose elements must all be of the same type. Elements can be assigned to an array or retrieved from it using an index. C# arrays are zero-based, meaning that the first element's index is always zero:

// Declare array with explicit size (size is 2)
int[] twoInts = new int[2];

// Assign second element by index
twoInts[1] = 8;

// Retrieve the second element by index
twoInts[1] == 8; // => true

// Check the length of the array
twoInts.Length == 2; // => true

Arrays can also be defined using a shortcut notation that allows you to both create the array and set its value. As the compiler can now tell how many elements the array will have, the length can be omitted:

// Three equivalent ways to declare and initialize an array (size is 3)
int[] threeIntsV1 = new int[] { 4, 9, 7 };
int[] threeIntsV2 = new[] { 4, 9, 7 };
int[] threeIntsV3 = { 4, 9, 7 };

Arrays can be manipulated by either calling an array instance's methods or properties, or by using the static methods defined in the Array class.

Iteration

An array is also a collection, which means that you can iterate over all its values using a foreach loop:

char[] vowels = new [] { 'a', 'e', 'i', 'o', 'u' };

foreach (char vowel in vowels)
{
    // Output the vowel
    System.Console.Write(vowel);
}

// => aeiou

One could use a for loop to iterate over an array:

char[] vowels = new [] { 'a', 'e', 'i', 'o', 'u' };

for (int i = 0; i < vowels.Length; i++)
{
    // Output the vowel
    System.Console.Write(vowels[i]);
}

// => aeiou

However, generally a foreach loop is preferrable over a for loop for the following reasons:

  • A foreach loop is guaranteed to iterate over all values. With a for loop, it is easy to miss elements, for example due to an off-by-one error.
  • A foreach loop is more declarative, your code is communicating what you want it to do, instead of a for loop that communicates how you want to do it.
  • A foreach loop is foolproof, whereas with for loops it is easy to have an off-by-one error.
  • A foreach loop works on all collection types, including those that don't support using an indexer to access elements.

To guarantee that a foreach loop will iterate over all values, the compiler will not allow updating of a collection within a foreach loop:

char[] vowels = new [] { 'a', 'e', 'i', 'o', 'u' };

foreach (char vowel in vowels)
{
    // This would result in a compiler error
    // vowel = 'Y';
}

A for loop does have some advantages over a foreach loop:

  • You can start or stop at the index you want.
  • You can use any (Boolean) termination condition you want.
  • You can skip elements by customizing the incrementing of the loop variable.
  • You can process collections from back to front by counting down.
  • You can use for loops in scenarios that don't involve collections.

Related Topics:

  • You should be aware that C# supports multi-dimensional arrays like int[,] arr = new int[10, 5] which can be very useful.
  • You should also be aware that you can instantiate objects of type System.Array with Array.CreateInstance. Such objects are of little use - mainly for interop with VB.NET code. They are not interchangeable with standard arrays (T[]). They can have a non-zero lower bound.

Both the above topics are discussed more fully in a later exercise.

Edit via GitHub The link opens in a new window or tab

Learn Arrays

Practicing is locked

Unlock 10 more exercises to practice Arrays