2. Arrays
• If you need to work with multiple objects of
the same type, you can arrays.
• Simple Arrays
– If you need to use multiple objects of the same
type, you can use an array. An array is a data
structure that contains a number of elements of
the same type.
3. Array Declaration & Array Initialization
• The array cannot be resized after the size was
specified without copying all elements.
int[] myArray;
myArray = new int[4];
Using an array initializer
int[] myArray = new int[4] {4, 7, 11, 2};
int[] myArray = new int[] {4, 7, 11, 2};
int[] myArray = {4, 7, 11, 2};
4. Accessing Array Elements
• After an array is declared and initialized, you can access
the array elements using an indexer. Arrays only
support indexers that have integer parameters.
– int[] myArray = new int[] {4, 7, 11, 2};
– int v1 = myArray[0]; // read first element
– int v2 = myArray[1]; // read second element
– myArray[3] = 44; // change fourth element
• If you use a wrong indexer value where no element
exists, an exception of type
IndexOutOfRangeException is thrown.
5. • If you don ’ t know the number of elements in
the array, you can use the Length property
for (int i = 0; i < myArray.Length; i++)
{
Console.WriteLine(myArray[i]);
}
Rajpat Systems
7. Using an array initializer
• When using an array initializer, you must
initialize every element of the array. It is not
possible to leave the initialization for some
values.
8.
9. Jagged Arrays
• A jagged array is more flexible in sizing the array.
• With a jagged array every row can have a different
size.
int[][] jagged = new int[3][];
jagged[0] = new int[2] { 1, 2 };
jagged[1] = new int[6] { 3, 4, 5, 6, 7, 8 };
jagged[2] = new int[3] { 9, 10, 11 };
10. for (int row = 0; row < jagged.Length; row++)
{
for (int element = 0; element < jagged[row].Length; element++)
{
Console.WriteLine(“row: {0}, element: {1}, value: {2}”,
row, element, jagged[row][element]
);
}
}
11. foreach Statement
• The C# foreach statement is not resolved to a foreach statement in
the IL code. Instead, the C# compiler converts the foreach
statement to methods and properties of the IEnumerable interface.