Adding Items

Let's see how we can add items to arrays in C#.

Watch the YouTube video

Creating an Array

In this example, we will use string as the type for our array, but you can choose any type you want: int, double, Object, array etc.

string[] fruits = new string[];
  • the square brackets [] show that we are dealing with an array;
  • the new keyword shows that the variable is an Object (reference type).

Fixed size

Unfortunately, we need to specify the size of the array when we create it.

Arrays in C# are not dynamic, in the sense that their size must be specified right at the beginning.

string[] fruits = new string[4];

Now, the size is 4 which means it can hold 4 items.

Indexers

One thing to remember is that computers do not count like we count:

  • we start by counting from 1 (1, 2, 3...),
  • whereas computers count from 0 (0, 1, 2, 3...). 😲

Because of that, array indexes range from 0 to array.Length - 1.

Adding items

We can start putting items in some positions:

fruits[0] = "apple";
fruits[1] = "cherry";

TIP

Notice that you don't have to fill all the positions of the array.

We've just added 2 even though we had 4 positions available. 😉

Let's try adding 3 more items and see what we get:

fruits[2] = "pineapple";
fruits[3] = "plum";
fruits[4] = "peach";

IndexOutOfRangeException

And we get the following exception: System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

This happend because we tried to add way to many items and it was caused by adding the peach 🍑:



 

fruits[2] = "pineapple";
fruits[3] = "plum";
fruits[4] = "peach";

So, essentially, we cannot:

  • change the size of the array;
  • add too many items to it;
  • ...
  • do so many things 😩

Throwing table

Giphy

List

This is where the Generic List comes into play ⏯. I am going to cover it soon...

List vs Arrays

Still, there are many use cases for the arrays and we don't just throw them in the trash because they cannot resize themselves 😕.

Maybe, in some scenarios this is the exact behaviour that what we want 😃

We can remove that line and try to display the values:

for(var i = 0; i < fruits.Length; i++)
{
    Console.WriteLine(i + ". " + fruits[i]);
}

So, this array has items from fruits[0] to fruits[3].

Summary

So, this is how you can add items to arrays. Next, I am going to show you a faster, shorter way of doing declaration and initialization in one line. 😉