Work with multiple data values with arrays

Arrays are a basic feature of the .NET languages. They allow you to easily work with multiple data items in one container. Tony Patton tells you more about using arrays in your code.

Arrays are a basic feature of most development languages. Arrays are mechanisms that allow you to treat several items as a single collection and to easily work with multiple data values. The .NET Framework provides array support in a variety of ways. In this article, I examine the basics of using arrays to work with various data values.

The basics

Microsoft .NET supports single-dimensional, multi-dimensional, and jagged arrays (array of arrays). Individual array elements are accessed using an index value. All of the array elements must be of the same type. A C# array can be created using the following syntax:

data_type[] arrayName = new data_type[size];

Using this syntax, the following code creates an array of integers capable of holding 10 values. Once created, the array is populated and displayed.

int[] testArray = new int[10];
for (int i=0; i < 10; i++) {
testArray[i] = i;
}
for (int j=0; j < 10; j++) {
Console.Write(testArray[j].ToString());
}

As the previous example demonstrates, C# arrays index references begin with zero. The last element in a C# array is the size of the array minus one. Individual array elements are referenced with the array name followed by the index value in brackets. VB.NET array syntax is similar, as the following VB.NET version of our example demonstrates.

Dim testarray(9) As Integer
Dim i, j As Integer
For i = 0 To 9
testarray(i) = i
Next i
For j = 0 To 9
Console.WriteLine(CStr(testarray(j)))
Next j

VB.NET uses parentheses as opposed to C#'s brackets. The big difference is declaring the array's size. C# accepts the array's actual count of the items, while VB.NET uses the largest index value so it corresponds to the actual values in the array (with the count beginning at zero).

At this point, I've focused on working with one-dimensional arrays, but you can easily create arrays with more than one dimension. The C# code in Listing A creates a three-by-three array and populates it like a game of tic-tac-toe as an example. With a two-dimensional array, the first index value is the row and the second value the column. Listing B contains the equivalent VB.NET code.

As the previous examples demonstrate, you can populate the array after creation, but you can also initialize it with values as well. Values may be assigned to the array by enclosing them in curly braces following the array declaration. The C# example in Listing C creates an array of string values for the 12 months of the year. Listing D contains the equivalent VB.NET code.

The code declares the string arrays and assigns the 12 values. In addition, it uses the array GetUpperBound method to retrieve the size of the array and use it to loop through and display individual array values. Let's take a closer look at other available methods for working with arrays.

Methods

In .NET, all array types are implicitly derived from the System.Array class. Furthermore, arrays are always reference types allocated on the managed heap. This means array variables contain a reference to the array and not the array itself. The following list contains some of the properties and methods of the System.Array class:

  • Length: Returns a 32-bit integer that represents the total number of elements in all the array dimensions.
  • Rank: Returns the number of dimensions of the array.
  • BinarySearch: Searches a one-dimensional sorted array for a value, using a binary search algorithm.
  • Clear: Allows you to clear a portion of the entire array.
  • ConvertAll: Converts an array of one type to an array of another type.
  • Copy: Copies a range of elements in one array to another array and performs typecasting and boxing as required.
  • CopyTo: Copies all the elements of the current one-dimensional array to the specified one-dimensional array.
  • Exists: Determines whether the specified array contains elements that match the conditions defined by the specified predicate.
  • Find: Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire array.
  • ForEach: Performs the specified action on each element of the specified array.
  • GetLength: Returns the length of the specified dimension of the array.
  • GetLowerBound: Returns the lower bound of the specified dimension in the array.
  • GetUpperBound: Returns the upper bound of the specified dimension in the array.
  • GetValue: Returns the value of the specified element from the array.
  • IndexOf: Returns the index of the first occurrence of a value in a one-dimensional array or in a portion of the array.
  • LastIndexOf: Returns the index of the last occurrence of a value in a one-dimensional array or in a portion of the array.
  • Resize: Changes the size of an array to the specified new size.
  • Reverse: Reverses the order of the elements in a one-dimensional array or in a portion of the array.
  • Sort: Sorts the elements in one-dimensional array objects.

I've used the GetUpperBound method to scroll through the items in the array. It accepts a value indicating which dimension to return since the array may be multi-dimensional. You can also use the GetLength method to return the size. I can alter a previous example to use it along with the Rank property to return the number of dimensions as the example in Listing E illustrates.

The code continues only if the number of dimensions (rank) is two, and the GetLength method is used to control the number of times the for loop processes. Listing F contains the equivalent VB.NET code.

Easily handle multiple values

Arrays are a basic feature of almost every development language. They make it easy to handle multiple elements (that are the same data type). In a future article, I'll examine sorting the contents of an array.

Miss a column?

Check out the .NET Archive, and catch up on the most recent editions of Tony Patton's column.

Tony Patton began his professional career as an application developer earning Java, VB, Lotus, and XML certifications to bolster his knowledge.