C# arrays are similar to ones in C/C++:
- zero based
- stored on heap (not stack)
- square brackets [] are used in their declaration
- once declared, their size can't be changed
However in addition to that, they have some extra features (some inherated from System.Array class):
- Length property which returns the size of an array
- methods for copying arrays in one go
How to declare an array:
int[] myNewArray; // uninitialized array variable of int type
int[] myNewArray = new int[15]; // declaring a variable and initializing array of 15 elements (they are initialized to 0 by default)
int[] myNewArray = {9, 3, 7, 2}; // creating and initializing an array at the same time - it's size is 4 = the number of elements
How to iterate through an array & access array elements:
There are two ways: the traditional for loop:
for(int iIndex=0; iIndex
{
Console.WriteLine(myNewArray[iIndex]);
}
and the new foreach loop:
foreach(int arrayElement in myNewArray)
{
Console.WriteLine(arrayElement);
}
How to copy an array:
// The First way of copying arrays - using CopyTo method
int[] sourceArray = {9, 3, 7, 2};
int[] targetArray = new int[sourceArray.Length]; // target array must be exactly the same size
sourceArray.CopyTo(targetArray, 0); // 0 is the starting index
// The Second way of copying arrays - using Array.Copy method
int[] sourceArray = {9, 3, 7, 2};
int[] targetArray = new int[sourceArray.Length]; // target array must be exactly the same size
Array.Copy(sourceArray, targetArray, targetArray.Length);
// The Second way of copying arrays - using Clone method
int[] sourceArray = {9, 3, 7, 2};
int[] targetArray =(int[]) sourceArray.Clode(); // Clone returns object data type, so casting is required
All these three methods use "shallow" copying, meaning that if copying an array of object references, only the references will be copied and not the objects they are reffering to.
Arrays are fine for simple stuff. For more complicated things there are collections... which will be explained later
|