Creating Arrays
The Array class is abstract, so using constructor array class can not be created.To create an arrays we use the static CreateInstance() method.By this way type of the elements in advance is not necessary to be known, as the type is passed to the CreateInstance() method as a Type object.
Array MyArray= Array.CreateInstance(typeof(int), 5); //( type of Array,Size of Array)
for (int i = 0; i < 5; i++)
{
MyArray.SetValue(33, i);
}
for (int i = 0; i < 5; i++)
{
Console.WriteLine(MyArray.GetValue(i));
}
Copying Arrays
Arrays are reference types, assigning an array variable to another one it need two varriable referencing to the same array. For copying arrays, the array implements the interface ICloneable. The Clone() method that is defined with this interface creates a shallow copy of the array.
If the array contains reference types, the elements are not copied, just the references
Car[] cars= {
new Car("Car", "Toyota"),
new Person("Bike", "Yahamaha")
};
Car[] CarClone = (Car[])CarClone .Clone();
int[] intArray2 = (int[])intArray1.Clone();
Sorting Arrays
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. Simple types such as System.String and System.Int32 implement IComparable, so you can sort elements containing these types.
string[] names = {
"Subhamay",
"Chaki",
"Alok",
"Gautam"
};
Array.Sort(names);
foreach (string name in names)
{
Console.WriteLine(name);
}

No comments:
Post a Comment