C# Array

We are going to dig into “Arrays”. We will look at different ways to define and use an array. We’ll also look into what other things we can do with Arrays.

Overview

In most cases in programming, you would need to work on a set of data.

For example, you are creating a program to compute the grades of students, you don’t want to create a grading system for only one student, instead you want to have it for the entire class or perhaps all the students at the school.

Or in the case of the ordering system, you will not get an order from a single customer but from multiple or all the customers. And customers won’t order a single item but rather multiple items.

Sets of data are typical in applications, consider a set of songs in the Spotify Playlist or a set of pictures in your Facebook album or set of “Stories” in your Instagram highlights.

Because it is typical and common in applications, creating a set of data is a fundamental feature of many programming languages.

What is an Array?

One of the easiest ways to create and work on a set of data in C# is using Array.

An array is a fixed-size list of elements that can be accessed using a positional index number.

It’s like declaring a variable but instead of having only a single value for that variable, in an array you can have a fixed-size but multiple values.

📎 To access each value, you must specify the order of that value in the list. The position number of values starts with 0 (zero) and not 1.

Hence, if I have an array with these values: 85, 75, 90, 83 – and I want to get 90, I will specify its position number which is 2.

Important points about array:

  • Arrays in C# are strongly typed. If you declared an array of integers, you can’t give it a value of string.

  • In C#, the index is zero-based meaning that the first element in an array has an index number of 0. Consider this example:

      [0] "Brain Rules"
      [1] "Pragmatic Programmer"
      [2] "Harry Potter and the Half-Blood Prince"
      [3] "The Alchemist"
    
  • Arrays are fixed size which means that we must define the desired size of the array when we initialize it, and once initialized, we cannot adjust that size.

  • Arrays in C# are derived from System.Array class or namespace.

Declaring and Populating an Array

Like all variables before you can use an array, you need to declare it.

In creating or declaring an array, we need to answer the question, “what type of set of data (collection)?"

We need to consider the type of element that the array will contain. For our example, if we want to work with a set of book titles, then we want an array of strings. If we want to work with a set of grades, then we want an array of double.

Declare an Array

To declare an array, we specify the array element type (or data type) followed by square brackets and the name to reference the array.

string[] booktitles;

In the above example, we specify a string type for the array elements. This particular array can then only hold string elements.

Arrays can hold any type, so we could use int here to declare an array of integers or DateTime to declare an array of dates as in the examples below:

int[] grades;

DateTime[] publishedDates;

Initialize an Array

Next is to put a starting value to the array variable or initialize it.

To initialize the array, we assign the array variable to a new array instance. We again specify the array element type, but here we must define the size of the array within the square brackets. A size of 4 means that there are 4 elements in this array and there positions are number 0 through 3.

string[] booktitles; //declaration

booktitles = new string[4]; //initialization

When an array is instantiated, it is initialized to contain the defined number of elements and each element is set to the default appropriate for the specified array element type. In our example, the array element type is string, so each array element is set to null, which is the default value for a string.

Now we have declared or created an array and given it a 4 as its size.

other ways…

  • Declaration and initialization can be done on a single line like this:

    string[] booktitles = new string[4];

  • Or we can use what we call the implicit data type var keyword like this:

    var booktitles = new string[4];

    Then because we have the array type defined on the right, we can use implicit typing with the var keyword, as shown here. C# will then implicitly determine the type of the booktitles variable based on the type declared on the right.

📎 These different ways are functionally equivalent such that it all declare and initialize an array variable but the last syntax (using implicit data type var) is preferred by many developer because it is less repetitive and easier to read.

📎 Note that the examples of array we have so far is single dimensioned meaning that it is a simple list of things. In C# and in many programming language, it is possible to create a multidimensional arrays and even an array of arrays.

Populating an Array

Once the array is declared and initialized, we populate the array by putting elements into the positions of the array.

We access the array elements using square brackets and the element index or position number.

    //using implicit data type var
    var booktitles = new string[4];

    //populating the elements of the array
    booktitles[0] = "Brain Rules";
    booktitles[1] = "Pragmatic Programmer";
    booktitles[2] = "Harry Potter and the Half-Blood Prince";
    booktitles[3] = "The Alchemist";

These replace the null values with actual book titles.

Alternatively, we can put the initialization, declaration and populating of value in one single line like below using a technique called Collection Initializer:

    //intialization, declaration and populating an array
    var booktitles = new[] {"Brain Rules", "Pragmatic Programmer", "Harry Potter and the Half-Blood Prince","The Alchemist" };

WARNING: If we try to put new element in the declared and initialized array, we’ll get an error because arrays are fixed-size and thus the size should be implicitly or explicitly declared in during declaration and initialization.

WARNING: If we try to put or populate an array element that’s not the data type of the array, we’ll also get an error of something like “cannot implicitly convert type int to string.”

⚡ Best Practices when declaring and populating an array ⚡

  • When you know you need to use and work on a set of data and that you already know the size, do consider using arrays. Arrays use memory efficiently and perform well.
  • Avoid using arrays when the size of the list is not known, such as when the data comes from a database. Instead, use one of the other list types such as List.
  • Do use a plural variable name for the array. A plural name implies that the variable holds multiple elements making the intent clearer.
  • When you already know the elements the array will contain, do use collection initializers. They provide a much clearer syntax for declaring and populating an array.
  • Avoid manually populating an array. When manually populating an array, it is easy to misnumber the index and cause hard-to-find bugs or generate a runtime exception.

Retrieving an element from Array

Similar to populating where we use square brackets and array index to put values to the array, we will use the same technique to retrieve values from an array.

To retrieve an element value from the array, we use the array variable and identify the desired element index within square brackets.

Since the array is zero-based, the first element has an index of 0 and so on. Consider the following code and output below:

//intialization, declaration and populating an array
var booktitles = new[] {"Brain Rules", "Pragmatic Programmer", 
                "Harry Potter and the Half-Blood Prince", "The Alchemist" };
                    
//retrieving an element from an array
Console.WriteLine(booktitles[0]);
Console.WriteLine(booktitles[1]);
Console.WriteLine(booktitles[2]);
Console.WriteLine(booktitles[3]);

Output: implicit

If we try to retrieve an element that is beyond the size of the array or out of range like the example below. The compiler doesn’t catch it but running the code will throw an error.

//intialization, declaration and populating an array
var booktitles = new[] {"Brain Rules", "Pragmatic Programmer",
                "Harry Potter and the Half-Blood Prince",
                "The Alchemist" };
            
//retrieving an element from an array
Console.WriteLine(booktitles[0]);
Console.WriteLine(booktitles[1]);
Console.WriteLine(booktitles[2]);
Console.WriteLine(booktitles[3]);
Console.WriteLine(booktitles[4]);

Output: implicit

⚡ Best Practices when retrieving elements from an array ⚡

  • Be careful when referencing array elements by index. An index that is out of bounds will throw a runtime exception.
  • Avoid retrieving elements by index when you need all the elements. Instead, iterate through the elements using for or foreach.

Iterating through an Array

Oftentimes instead of retrieving the elements individually, you need to iterate through all or some of the elements in an array.

C# provides two ways to iterate over elements in an arrayforeach and for.

using foreach

The foreach statement accesses each item or element in the array without the need for manual indexing.

It repeats a group of statements for each element in an array. The elements are processed in index order from index 0 up to the last index.

Here’s an example using foreach:

//intialization, declaration and populating an array
var booktitles = new[] {"Brain Rules", "Pragmatic Programmer",
                "Harry Potter and the Half-Blood Prince",
    "The Alchemist" };
            
//iterating through an array
foreach (var title in booktitles)
{
    Console.WriteLine($"The book title is {title}");
}

Output: implicit

⚡ Important points when using foreach ⚡

  • Some important points in using foreach is the iteration variable (var title) is a read-only local variable that represents the current element in the array.

  • foreach also always goes through all of the elements in the array and you need to implement logic to skip some elements.

  • When using foreach, the element itself cannot be changed. For example, say we want to change each element to lowercase. If we try to change the iteration variable, Visual Studio marks it as an error, cannot assign to color because it is a foreach iteration variable, so we can’t modify the value here. See example below: implicit

using for

The for statement repeats a group of statements while a specific condition is true. It iterates using an integer value and to access array elements we can use that integer value.

Consider the example code below and its output:

//intialization, declaration and populating an array
var booktitles = new[] {"Brain Rules", "Pragmatic Programmer",
                "Harry Potter and the Half-Blood Prince",
                "The Alchemist" };
            
//iterating through an array using for loop
for (int i = 0; i < booktitles.Length; i++)
{
    booktitles[i] = booktitles[i].ToUpper();
}

//iterating through an array using foreach
foreach (var title in booktitles)
{
    Console.WriteLine($"The book title is {title}");
}

Output: implicit

⚡ Important points when using for ⚡

  • Inside the for, we change each element to lowercase. We accessed an element using the initializer variable (int i) as an index and we used the ToUpper() string method to change the text to uppercase.

  • Unlike the foreach, with for, we can change the value of the element within the iteration and we could easily change this code to only process some of the elements. We could change the iteration to begin at 1 or end at 2, for example, or process every other element by incrementing the iterator by 2.

foreach vs for

  • foreach syntax is quick and easy while for syntax is a little more complex but is also more flexible.
  • foreach is useful when iterating all of the elements in an array. for is useful when iterating over only a subset of elements.
  • The foreach iteration variable that provides each array element is read-only, so we can’t modify array elements as they are iterated. Using the for syntax, we can modify the array elements as needed.
  • Use foreach to quickly iterate all of the elements of an array. Use for to iterate a subset of the elements of the array or to modify array elements as they are iterated.

🔚 end of document 🔚

References