Introduction To C# Arrays

Introduction To Arrays Banner Image

Introduction

Arrays are a fundamental data type in C# and form the basis for other data structures and implementations. This is because it has a simple interface, method structure, and basic checks. It has speed and doesn't have a big memory footprint. But the downside is that you manage the array,and the contents and check to see when it's safe to add, remove, or grow the array.

What Are Arrays In C#?

Example single dimensional array with popular destinations below.

Index0123
Paris:The Eiffel TowerNew York City:The Statue of LibertyTokyo:The Tokyo TowerBarcelona:The Sagrada Familia

Arrays are structured together as continuous blocks in memory. So if I have an array that has 4 items for example. The index starts at 0 and goes to 3.

How To Create An Array?

Arrays can be created with the following syntax. The brackets after the string, object, or class denote that this is an array. Then the new keyword is used. Then brackets again but this number is the size of the array that will be initialized in memory. You can also pass in a variable for the size.

string[] destinationsArray = new string[4];//Create an array of size 4

Assign Values To The Array

Once the array is created then I can assign value to the array. For assigning a value, we use the indexer property on the left side of the equals sign and then the location in the array where we want to give a value. Since there are 4 items in the array the first location in the array is 0 and the last value in the array is 3.

string[] destinationsArray = new string[4];//Create an array of size 4
destinationsArray[0] = "Paris:The Eiffel Tower";//Assign value to index 0
destinationsArray[1] = "New York City:The Statue of Liberty";//Assign value to index 1
destinationsArray[2] = "Tokyo:The Tokyo Tower";//Assign value to index 2
destinationsArray[3] = "Barcelona:The Sagrada Familia";//Assign value to index 3

foreach(string destination in destinationsArray)//Loop through all the values of the array
{
    Console.WriteLine($"destination:{destination}");//Print the values of the array
}
Code Output
destination:Paris:The Eiffel Tower
destination:New York City:The Statue of Liberty
destination:Tokyo:The Tokyo Tower
destination:Barcelona:The Sagrada Familia
For more examples of how to assign values to an array. I wrote this article going into the details of different ways of doing it in How To Assign Values to An Array

Initialize An Array

We can give array starting values, but the starting size needs to be set. This sets the size in the memory of the array and allocates the memory. Since we're creating an array of size 4, it also requires that initialized values count also needs to be 4, or else the program will not compile.

string[] destinationsArray = new string[4] { "Australia:The Sydney Opera House", "United States:The Grand Canyon", "Paris:Louvre Museum", "New York City:Empire State Building" };

foreach (string destination in destinationsArray)//Loop through all the values of the array
{
    Console.WriteLine($"destination:{destination}");/Print array values to screen
}
Code Output
destination:Australia:The Sydney Opera House
destination:United States:The Grand Canyon
destination:Paris:Louvre Museum
destination:New York City:Empire State Building
More Info On Array Initializers

There are more examples of how to initialize an array. I wrote the articles How To Initialize Arrays and Best Initializer To Get An Empty Array for more details analysis of initializing arrays.

C# Programming for Unity Game Development Specialization

COURSERA

C# Programming for Unity Game Development Specialization

4.7 (2,230 reviews)

Beginner level

No previous experience is necessary

3-months at 10 hours a week (At your pace)

$59 / month or audit, and financial aid available

If you want to learn more about C# then check out this course on Coursera. It's a 3 month course to take you through the basics of C#.

You can get started with programming using C# and apply it to Unity games in this beginner-level program. Facilitated by the University of Colorado, the program offers a chance to grasp the basics of C# and utilize the knowledge to develop Unity games.

[Full Disclosure: As an affiliate, I receive compensation if you purchase through this link]

Start Your 7-day Free Trial

Access Items In The Array

If I want to get a value from the array at a certain location then I need to use the indexer on the right side of the equals sign. Or in this case, we can use the indexer on the index value want to get the value and print it to the screen.

string[] destinationsArray = new string[4] { "China:The Great Wall", "Rome:The Colosseum", "Peru:Machu Picchu", "Egypt:The Pyramids of Giza" };

for(int i = 0;i < destinationsArray.Length; i++)//Loop through all the values of the array
{
    Console.WriteLine($"destination:{destinationsArray[i]}");//Use the indexer to print the values for each i. i goes from 0 to 3.
}
Code Output
destination:China:The Great Wall
destination:Rome:The Colosseum
destination:Peru:Machu Picchu
destination:Egypt:The Pyramids of Giza

Get The Size oF An Array

Another important feature of arrays is the length property. This is needed so that you can check to see if the index your using the access the array is valid. Otherwise, you might hit an out-range exception. So this is a good check to always have when accessing the array.

string[] destinationsArray = new string[4] { "London:The Tower Bridge", "United States:The Golden Gate Bridge", "Nepal:The Mount Everest Base Camp", "Zambia and Zimbabwe:The Victoria Falls" };

Console.WriteLine($"destination array length:{destinationsArray.Length}");//Print length to the screen

for (int i = 0; i < destinationsArray.Length; i++)
{
    if (i >= 0 && i < destinationsArray.Length)//check if the index is in the array
    {
        Console.WriteLine($"destination:{destinationsArray[i]}");//Use the indexer to print the values for each i. i goes from 0 to 3.
    }
}
Code Output
destination array length:4
destination:London:The Tower Bridge
destination:United States:The Golden Gate Bridge
destination:Nepal:The Mount Everest Base Camp
destination:Zambia and Zimbabwe:The Victoria Falls
Get Latest Updates