The Array Class:
The following code shows you how an Array class works. In the following example we would see how to declare an array how to set and get values from the particular array.
ONE DIMENSIONAL ARRAY
Creating an array which can hold string type data in it , also you have to mention the length of that string array. CreateInstance(Type t , int length) is the static function of Array class
var ar = Array.CreateInstance(typeof(string), 5);
Now, if you display the length of array like:
Console.Write(ar.Length); // will display 5
Now, inserting values in the array: for this there is function of array class .SetValue() which takes two arguments one is the object value and the second one how to insert the object at mentioned index.
ar.SetValue("osama", 0); // here inserting osama at 0th index
ar.SetValue("saad", 1);
ar.SetValue("bilal", 2);
ar.SetValue("maryam", 3);
ar.SetValue("amal", 4);
you see above, how we inserted the 5 values in our array.
How to get the value from the array: for this there is function of array class .GetValue() which takes one argument index , where we have to specify at what index we want to get value from, it returns object.
object obj = ar.GetValue(2);
Console.Write(obj); //will display bilal
Casting the data into string while getting from array because our array is of string data type we want the data in string not in object.
string str = (string) ar.GetValue(2);
Console.Write(str); //will display bilal
Or,
string str = ar.GetValue(2).ToString();
Console.Write(str); //will display bilal
In a same way you can define array of any type, just change the data type in typeof() function.
var ar2 = Array.CreateInstance(typeof(int), 5);
TWO DIMENSIONAL ARRAY
Creating two dimensional array of integer data type.
CreateInstance(Type t , int length1 , int length2) is also a static function which takes three arguments first type of array second the length1 for rows and length2 for columns of two dimensional array.
var ar = Array.CreateInstance(typeof(int), 2, 3);
Same way, inserting values in array:
ar.SetValue(12, 0, 1); // inserting ‘12’ in 1st column of 0th row
Same way, getting values from array: function of array class .GetValue() which takes two argument index1 and index2 , where we have to specify at what index we want to get value from, it returns object.
object obj = ar.GetValue(0, 1);
Console.Write(obj); //will display 12
0 comments:
Post a Comment