Simple Arrays
An array is a data structure that contains object/data of same typeArray Declaration
An array is declared by defining the type of the elements inside the array followed by empty brackets and a variable name; for example, an array containing integer elements is declared like this:
int [] sampleArray
Using Reference Types
arrays can be declared of a type of a custom class. Let Us take an example of "Product" class having two constructor an ToString() method
public class Product
{
public Product() //default constructor
{
}
public Product(string name, string description) //parametrized constructor
{
this.name = name;
this.description = description;
}
private string _name;
private string _description;
public string ProductName
{
get { return _name; }
set { _name = value; }
}
public string Description
{
get { return _description; }
set { _description = value; }
}
public override string ToString()
{
return name + " " + description;
}
}
Now Declaring an array of four is similar to declaring an array of int:
Product [] myProduct = new Product[4]
Here memory must be allocated for each array element otherwise a NullReferenceException will be thrown.
Multidimensional Arrays
1-dimension array are indexed by a single integer. A multidimensional array is indexed by two or more integers.
How To Declare Two Dimension Array
int[,] myarray = new int[3, 3];
myarray[0, 0] = 1;
myarray[0, 1] = 2;
myarray[0, 2] = 3;
myarray[1, 0] = 4;
myarray[1, 1] = 5;
myarray[1, 2] = 6;
myarray[2, 0] = 7;
myarray[2, 1] = 8;
myarray[2, 2] = 9;
How To Declare Three Dimension Array
int[,,] threedim = {
{ { 1, 2 }, { 3, 4 } },
{ { 5, 6 }, { 7, 8 } },
{ { 9, 10 }, { 11, 12 } }
};
Jagged Arrays
A 2-dimensional array has a rectangular size (for example 3 by 3 elements). A jagged array is more flexible in sizing the array. With a jagged array every row can have a different size.
a 2-dimensional array that has 3x3 elements with a jagged array. The jagged array can contains three rows where the first row would have elements, the second row would have elements, and the third would have three elements.
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 };
Itaration through for loop
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]);
}
}

No comments:
Post a Comment