C# Arrays
By Stephen Armstrong // December 13, 2019
Learn how to create and use Arrays.
An array allows you to make a collection of data types and classes.
In C# there are many types of collections (such as List and Dictionary), and Arrays may seem inflexible or “old fashioned” compared to using them. But arrays can be effective and faster in many applications.
Arrays can contain types or objects, for example:
// Arrays of types
int [] numbers;
bool [] switches;
float [] timers;
// Arrays of classes
Map [] levels;
Enemy [] enemies;
Bullet [] bullets;
Create an Array
If you know how many entries your array will have when it starts, then you can simply create it with that many starting entries.
// Create an int array with five empty entries - these entries are 0 by default.
int [] arrayTest1 = new int[5];
If you know the exact values and order of the values your array will have when it starts, then you can also set them when you create the array.
// Create an int array with five set entries.
int [] arrayTest1 = new int [] { 5, 4, 3, 2, 1 };
Getting and Setting an Array Value
To get a an array value, use its index (the number between the square brackets [ ]). Below is an example:
// Create an int array with five set entries.
int [] arrayTest = new int [] { 5, 4, 3, 2, 1 };
// Outputs the value of arrayTest[3] - will be 2
System.Console.WriteLine("arrayTest[3] == {0}", arrayTest[3]);
Setting a value to an array is similar. See the below code as an example:
// Create an int array with five set entries.
int [] arrayTest = new int [] { 5, 4, 3, 2, 1 };
// Set a new value to the first entry of the array.
arrayTest[0] = 2020;
// Outputs the value of arrayTest[0]
System.Console.WriteLine("arrayTest[0] == {0}", arrayTest[0]);
Add a New Entry to Array
You cannot just add a new entry to a C# array. First you must resize the array. See below for an example.
// Create an int array with five set entries.
int [] arrayTest = new int [] { 10, 20, 30, 40, 50 };
// This will be added to the array.
int valueToAdd = 60;
// Resize the Array. The new length is the current length + 1.
System.Array.Resize(ref arrayTest, arrayTest.Length + 1);
//Add valueToAdd to the end of the array. As Arrays start from 0, you must remove 1 from the length to get the last entry.
arrayTest[arrayTest.Length - 1] = valueToAdd;
// This for loop goes through each entry and displays them in the Output.
for (int i = 0; i < arrayTest.Length; i++)
{
System.Console.WriteLine("arrayTest[{0}] == {1}", i, arrayTest[i]);
}
If you run this code you will get the following:
Shrink an Array
If you want to remove the last entry of the array, you can simply resize it to its current length -1. See the below code for an example.
// Remove the last entry by resizing the array to its current length - 1
System.Array.Resize(ref arrayTest, arrayTest.Length - 1);
Shrinking an array by removing a specific entry (including the first entry) can be more complicated, but a straightforward way is simply to create a new array with the specific entry excluded. The below code is an example of this method:
// Create an int array with five set entries.
int [] arrayTest = new int [] { 10, 20, 30, 40, 50 };
// The index to remove (arrayTest[2] = 30)
int indexToRemove = 2;
// Create a new array with one fewer entry than arrayTest.
int [] resizedArray = new int[arrayTest.Length - 1];
// Make an internal counter for the For loop.
int adjustedCounter = 0;
// This For loop goes through arrayTest and adds values to the resizedArray based on the adjustedCounter.
for (int i = 0; i < arrayTest.Length; i++)
{
// Only add values if they are not the entry to remove.
if (i != indexToRemove)
{
// Set the entries to the new array using the adjustedCounter.
resizedArray[adjustedCounter] = arrayTest[i];
// Increment the adjustedCounter to compensate for the removed entry.
adjustedCounter++;
}
}
// Overwrite the original array.
arrayTest = resizedArray;
// This for loop is to output every entry of the new array.
for (int i = 0; i < arrayTest.Length; i++)
{
System.Console.WriteLine("adjusted arrayTest[{0}] == {1}", i, arrayTest[i]);
}
This may not be the most efficient way of doing so, and resizing Arrays in general can be quite resource intensive. If you will be routinely resizing an Array, then another collection type may be better.
Sort an Array
There is an inbuilt function for sorting arrays – System.Array.Sort().
See the below code example, where an unsorted string array of animal names is created and then sorted.
// Create a new unsorted string array.
string [] animals = new string [] { "Zebra", "Dog", "Cat", "Lion", "Jaguar", "Tiger", "Gorilla", "Duck", "Beaver", "Aardvark" };
// This for loop goes through each entry and displays them in the Output.
for (byte i = 0; i < animals.Length; i++)
{
System.Console.WriteLine("Unsorted animals entry {0} == {1}", i, animals[i]);
}
// Sort the animals array.
System.Array.Sort(animals);
// This for loop goes through each entry and displays them in the Output.
for (byte i = 0; i < animals.Length; i++)
{
System.Console.WriteLine("Sorted animals entry {0} == {1}", i, animals[i]);
}
When you run this code, check the Output to see the listed unsorted and sorted arrays:
Further reading
Future tutorials may go into detail about other data collection types.