Simple Arrays
Array Declaration
An array is declared by defining the type of the elements inside
the array followed by empty brackets and a variable name
E.g.: int[] myArray;
Array Initialization
After declaring an array, memory must be allocated to hold all the
elements of the array.
An array is a reference type, so memory on the heap must be
allocated.
This is done by initializing the variable of the array using the new
operator with the type and the number of elements inside the
array.
Here you specify the size of the array.
E.g. myArray = new int[4];
Instead of using a separate line for the declaration and
initialization, you can declare and initialize an array in a single line
Multidimensional Arrays
Ordinary arrays (also known as 1-dimensional arrays) are indexed
by a single integer. A multidimensional array is indexed by two or
more integers.
The following matrix shows the mathematical notation for a 2dimensional array that has three rows and three columns. The
first row has the values 1, 2 and 3, whereas the third row has the
values 7, 8 and 9.
123
456
789
Declaration & Initialization of Two Dimensional Array
int[,] twodim = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
Note: When using above array initializer, you must initialize every
element of the array. It is not possible to leave the initialization
for some values.
Jagged Arrays
Jagged Array is the kind of array which has array as its elements
Two Dimensional Array
Jagged Array
123
12
456
789
34567
8 9 10
Array Class
Declaring an array with brackets is a C# notation of using the
Array class.
Using the C# syntax behind the scenes creates a new class that
derives from the abstract base class Array.
Properties
Property
Description
Length
LongLength
Rank
Creating Arrays
The Array class is abstract, so you cannot create an array by using
a constructor.
However, instead of using the C# syntax to create array instances,
it is also possible to create arrays by using the static
CreateInstance() method.
This is extremely useful if you dont know the type of the
elements in advance, as the type can be passed to the
CreateInstance() method as a Type object.
The following example shows how to create an array of type int
with a size of 5.
Array intArray1 = Array.CreateInstance(typeof(int), 5);
for (int i = 0; i < 5; i++)
{
intArray1.SetValue(33, i);
}
Sorting
The Array class implements a bubble-sort for sorting the elements in
the array.
The Sort() method requires the interface IComparable to be
implemented by the elements in the array.
string[] names = { "Christina", "Shakira", "Beyonce", "Gwen};
Array.Sort(names);
Reverse
Reverse Method is used to reverse the elements of the array
string[] names = { "Christina", "Shakira", "Beyonce", Gwen};
Array.Reverse(names);
Copying Arrays
The Clone() method that is defined with this interface creates a
shallow copy of the array.
int[] intArray2 = (int[])intArray1.Clone();
THANK YOU