I mentioned that all array objects in C# are implicitly objects of the System.Array class. System.Array contains useful methods and properties which you can use. The Length property, [8] discussed earlier, is actually inherited from System.Array. Other methods can be used for creating, manipulating, searching, and sorting arrays.
[8] If you are not sure of C# properties, just treat a property as a public field for now. See Chapter 20 for more information.
I shall introduce the following static methods in System.Array which can be useful for 1D arrays:
public static void Reverse (Array array)
public static void Sort (Array array)
public static int IndexOf (Array array, Object value)
Check out the API documentation for more details.
Reverse() takes in a 1D array and reverses the sequence of the elements stored in it. Here is a simple example of its use:
1: using System; 2: 3: public class TestClass{ 4: public static void Main(){ 5: string []Fruits ="apple","orange","banana","coconut"}; 6: Array.Reverse(Fruits); 7: 8: for (int i=0; i<4; i++) 9: Console.WriteLine(i + ":" + Fruits[i]); 10: } 11: }
Output:
c:expt>test 0:coconut 1:banana 2:orange 3:apple
Likewise, Sort() takes in a 1D array and sorts the elements in order. Replacing line 6 of the program above with this statement:
6: Array.Sort(Fruits);
results in this output:
c:expt>test 0:apple 1:banana 2:coconut 3:orange
IndexOf () takes in a 1D array and an object to be matched against the elements in the array. It returns the array index of the first match or -1 if no match is found. Examine the following program:
1: using System; 2: public class TestClass{ 3: public static void Main(){ 4: string []Fruits={"apple","orange","banana","coconut"}; 5: Console.WriteLine(Array.IndexOf(Fruits,"banana")); 6: } 7: }
Output:
c:expt>test 2
3.133.156.251