Lesson 4 – C# Arrays

Arrays in C# are used to store a collection of items. If you have to store a collection of data of the same data type, it is advisable to use arrays instead. In this lesson, you will see how to create Arrays in C#, how to store elements in C# arrays and how to update elements in C#.

Creating Arrays

To create an array you first have to define an array variable. To do so, you first define the type of the items that the array will store followed by opening and closing square brackets and the name of the array. Once the array variable is defined, you can store an array object in the array variable. To create an array object, the keyword “new” is used followed by the array type and opening and closing bracket. Inside the brackets, you specify the number of items that the array will contain. The following script creates an array named “week” with 7 items.

using System;

namespace C_Project
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] week = new string[7];
            week[0] = "Monday";
            Console.WriteLine(week[0]);

        }
    }
}

The output of the above script is as follows:

Monday

Inerting Item in Array

To insert an item in the array, you first have to select the location or index of the array where you want to store the item. Array index in C# starts from zero which means that the first element is stored at 0th index. In the following script, the weekday names “Monday” and “Tuesday” are stored in the first two indexes of the “week” array:

using System;

namespace C_Project
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] week = new string[7];
            week[0] = "Monday";
            week[1] = "Tuesday";
            Console.WriteLine(week[0]);
            Console.WriteLine(week[1]);
        }
    }
}

The output of the above script is as follows:

Monday
Tuesday

Updating Array

To update an array, simply select the array index that you want to update and then assign it a new value. For instance, in the following example, we store “Sunday” at the first index and “Monday” at the second index of the “weeks” array. We then print the value at the first and second indexes of the week array on the console:

using System;

namespace C_Project
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] week = new string[7];
            week[0] = "Sunday";
            week[1] = "Monday";
            Console.WriteLine(week[0]);
            Console.WriteLine(week[1]);
        }
    }
}

The output of the above script is as follows:

Sunday
Monday

What’s Next?

In this lesson, you studied arrays in C#. In the next lesson, you will see conditional statements which are used for decision making in C#.