1. An Array is a Container of Elements
You've probably heard that computers can handle massive amounts of info. The conditional operator (if-else) and loops (for, while) definitely help with that. But you can't get far with just those, because you need to store the data you're working with somewhere.
For that, C#, like pretty much every programming language, has this awesome thing called arrays (Array). They're also sometimes called tables.
An array is a special object where you can store not just one value, but several.
If before we compared a variable to a box (where you can store some value), then an array is more like a box that's divided into sections inside. Each section in the "array-box" has its own number. The numbering, of course, starts from zero...
Or here's another analogy. Let's compare a regular house and an apartment building. A regular house is occupied by one family, but an apartment building is split into apartments. To send a letter to a family in a regular house, you just need the unique address. But to send a letter to a family in an apartment, you need the unique address of the building and the apartment number.
So, an array-variable is like an apartment building variable. You can store not just one value, but several. In this variable, there are several apartments (cells), and you can access each one by its number (index).
To do that, after the variable name, you put the index of the cell you want in square brackets. It's pretty simple:
array[index] = value;
Where array is the name of the array variable, index is the number of the cell in the array, and value is the value you want to put in that cell.
But let's first figure out how to create arrays.
2. Creating an Array of Elements in C#
Let's say your program needs to store 100 integers somewhere. Most likely, an array would be perfect for that. So how do you create one?
If we wanted to store just one integer, we'd use the int type, but if we want to store 100 integers, we probably need an array of type int. Here's what the code to create it looks like:
int[] array = new int[100];
Let's break down what's written here.
As you might have guessed, to the left of the equals sign is the declaration of a variable named array of type int[]. After the type int come square brackets, which kind of hint that you can store not just one value in these "boxes", but several.
To the right of the equals sign, we have "creating an object" (the word new) with 100 elements (cells) of type int. Not too hard either.
If, for example, we wanted to create an array with 20 cells to store floating point numbers, the code would look something like this:
double[] vals = new double[20];
The number of cells in an array is called the size of the array or length of the array. And because arrays can store a lot of values, they're also called containers.
Important fact: the size of an array container can't be changed after it's created.
You can create a new one, but you can't change the length of an already created container.
3. Working with Array Cells
Alright, we know how to create arrays, but how do you actually work with them?
Pretty much the same way as with regular variables, except after the array variable name, you always have to specify the cell number you're working with.
Array cell numbering always starts at zero. If we have an array with 10 elements, the numbers (indexes) of its cells are 0..9, if the array has 200 elements, then 0..199. And so on.
Examples:
int[] a = new int[10]; // Create an array with 10 elements of type int.
a[2] = 4; // Put the value 4 in the cell with index 2.
a[7] = 9; // Put the value 9 in the cell with index 7.
a[9] = a[2] + a[5]; // Put the sum of the values stored in cells 2
// (stores 4) and 5 (stores 0) into cell 9.
Here's what will be stored in memory after this code runs:
The column to the left of the array (in gray) is the numbers (indexes) of the cells. The cells store the entered values: 4, 9, and 4. Right after creation, array cells are filled with zeros.
Important. All array cells have the same data type. If we created an array of strings string, only strings can be stored in its cells. The data type of the array is set when it's created. You can't change the data type or the length of the array later.
4. Arrays in Memory
The pictures in the previous examples are a bit off.
When arrays are created (just like with strings), two blocks of memory are allocated: one for storing the array (the container) itself, and another for the variable that stores its address. The clarified situation is shown in the picture below:
The green part shows an array with 10 elements of type int and a variable of type int[] that stores the address (reference) of the array of type int in memory.
For comparison, the blue part shows a regular variable of type int that stores the value 199.
Kind of reminds you of how strings are stored in memory, right?
Exactly, strings. And just like with strings, "array type variables" can be assigned to each other:
int[] a = new int[10]; // Create an array with 10 elements of type int.
a[2] = 4; // Put the value 4 in the cell with index 2.
a[7] = 9; // Put the value 9 in the cell with index 7.
int[] b = a; // Save the address from variable a into variable b.
// Now a and b both point to the same array object in memory.
a[9] = b[2] + a[7]; // Put the sum of the values stored in cells 2 (stores 4) and 7 (stores 9)
// into cell 9 of the array object.
The array object will stay where it is, and the variables a and b will both store the same address (reference) to the same object. Check out the picture:
5. Working with Arrays in More Detail
You can create an array from absolutely any type. All you have to do is put square brackets after the type name. The general way to create an array looks like this:
type[] name = new type[count];
Where type is the type of the elements (cells) of the array that we'll store in the array. name is the name of the variable we'll use to access the array, and count is the number of cells in the array.
The example above shows the canonical form: creating an array variable and creating the array object. Actually, these are two independent things. You can create the array variable and the array object separately:
type[] name;
name = new type[count];
And one more important thing
You can use variables and even whole expressions as the array index and as the number of elements in the array.
Examples:
int n = 100;
int[] a = new int[n]; // Create an array with n elements
int n = 100;
int[] a = new int[n * 2 + 3]; // Create an array with 203 elements
int n = 100;
int[] a = new int[n];
a[n-1] = 2; // a[99] = 2;
a[n-2] = 3; // a[98] = 3;
a[n/5] = a[n-1] + a[n-2]; // a[20] = a[99] + a[98];
Going Out of Array Bounds
By the way, heads up: if you try to access an array cell by an index that doesn't exist in the array (in our case, that's any integer except 0..99), the program will crash with an error IndexOutOfRangeException — index out of array bounds.
6. Array Length
As we saw in the previous example, you can create an array variable separately and then assign it a value (a reference to an array object) somewhere in the code. You can even do this:
int[] array; // Create an array variable of type int[]
if (a < 10) // If variable a is less than 10,
array = new int[10]; // then create an array with 10 elements.
else // Otherwise
array = new int[20]; // create an array with 20 elements
So how do you work with such an array? How do you find out how many elements it has?
For that, arrays have a special property (variable) — length. And you can find out the length of an array with this expression:
array.Length;
Where array is the name of the array variable, and Length is the name of the property on the array object. You can't change the value in the Length property: you can assign the Length property to other variables, but you can't assign anything to it (the program just won't compile).
Here's how you can continue the previous example:
int[] array; // Create an array variable of type int[]
if (a < 10) // If variable a is less than 10,
array = new int[10]; // then create an array with 10 elements.
else // Otherwise
array = new int[20]; // create an array with 20 elements
for (int i = 0; i < array.Length; i++) // Loop through all elements of the array: from 0 up to array.Length — 1
{
Console.WriteLine(array[i]);
}
7. Facts About Arrays in C#
Let's sum up the known facts about arrays:
- Fact 1. An array consists of a bunch of cells.
- Fact 2. Access to a specific cell is done by specifying its number.
- Fact 3. All cells are of the same type.
- Fact 4. The initial value for all cells is 0 and null (if the cell stores an address), false (for type bool).
- Fact 5. string[] list — this is just a variable declaration: the container (array object) itself hasn't been created yet. To work with it, you need to create the array (container) and put it in this variable, and then you can use it. See the example below.
- Fact 6. When we create an array object (container), we need to specify its length — how many cells it has. This is done with a command like: new TypeName[n];
- Fact 7. You can find out the length of an array using the .Length property.
- Fact 8. After creating an array, you can't change the type of its elements or their number.
string s; // s is null
string[] list; // list is null
list = new string[10]; // The variable list stores a reference to an object — an array of 10 strings.
int n = list.Length; // n is 10
list = new string[0]; // Now list contains an array with 0 elements.
// The array exists, but it can't store any elements.
list = null;
Console.WriteLine(list[1]); // This will throw an error — the program will crash.
// list contains an empty reference — null
list = new string[10];
Console.WriteLine(list[10]); // This will throw an error — out of array bounds.
// If list contains 10 elements/cells, their allowed indexes are: 0 1 2 3 4 5 6 7 8 9 — a total of 10.
GO TO FULL VERSION