Friday, January 11, 2013

The System.Array Class in C#.NET


Every .NET array you create is automatically derived from System.Array. This class defines a number of helpful methods that make working with arrays much more palatable. Table 3-14 gives a rundown of some (but not all) of the more interesting members. 

Members of System.Array 

BinarySearch()  - This static method searches a (previously sorted) array for a given item. If the array is composed of custom types you have created, the type in question must implement the IComparer interface to engage in a binary search. 

Clear() - This static method sets a range of elements in the array to empty values (0 for value types; null for reference types). 

CopyTo() - This method is used to copy elements from the source array into the destination array. 

Length - This read-only property is used to determine the number of elements in an array. 

Rank - This property returns the number of dimensions of the current array. 

Reverse() - This static method reverses the contents of a one-dimensional array. 

Sort() - This method sorts a one-dimensional array of intrinsic types. If the elements in the array implement the IComparer interface, you can also sort your custom types.

Let’s see some of these members in action. The following code makes use of the static Reverse() and Clear() methods (and the Length property) to pump out some information about an array of strings named firstNames to the console: 

// Create some string arrays and exercise some System.Array members. 
static void Main(string[] args) 
// Array of strings. 
string[] firstNames = { "Steve", "Dominic", "Swallow", "Baldy"} ; 
// Print names as declared. 
Console.WriteLine("Here is the array:"); 
for(int i = 0; i < firstNames.Length; i++) 
Console.Write("Name: {0}\t", firstNames[i]); 
Console.WriteLine("\n"); 
// Reverse array and print. 
Array.Reverse(firstNames); 
Console.WriteLine("Here is the array once reversed:"); 
for(int i = 0; i < firstNames.Length; i++) 
Console.Write("Name: {0}\t", firstNames[i]); 
Console.WriteLine("\n"); 
// Clear out all but Baldy. 
Console.WriteLine("Cleared out all but Baldy..."); 
Array.Clear(firstNames, 1, 3); 
for(int i = 0; i < firstNames.Length; i++) 
Console.Write("Name: {0}\t", firstNames[i]); 
Console.ReadLine(); 

Do note that when you call the Clear() method on an array type, the items are not compacted into a smaller array. Rather, the emptied elements are simply set to default values. If you require a dynamically allocated container type, you will need to check out the types within the System.Collections namespace (among others).

No comments:
Write comments
Recommended Posts × +