Getting and Setting Values

You have to use the GetValue() and SetValue() functions in order to work with elements in arrays. SetValue() takes a reference to an object and the index or indices indicating the element to be set up. GetValue() takes an index or indices and returns an object reference. Because GetValue() returns a reference of type Object, you may have to cast this reference into the appropriate type before using it. Here's how you can set up and access the elements in a 2D array:

' Create a 2D array

Dim array2d As Array = Array.CreateInstance(GetType(Integer), 3, 3) ' Populate it

array2d.

,SetValuei

10,

0,

0)

array2d.

,SetValuei

11,

0,

1)

array2d.

,SetValue'

(12,

0,

2)

array2d.

,SetValue(

100,

1,

0

array2d.

,SetValue

110,

1,

1

array2d.

,SetValue!

(120,

1,

2

array2d.

,SetValue(

200,

2,

0

array2d.

,SetValue

210,

2,

1

array2d.

,SetValue(

220,

2,

2

' Print out all the elements

For i = array2d.GetLowerBound(0) To array2d.GetUpperBound(0) For j = array2d.GetLowerBound(1) To array2d.GetUpperBound(1)

Console.Write("{0} ", array2d.GetValue(i,j)) Next

Console.WriteLine() Next

While I'm on the subject of printing out array elements, it is worth mentioning GetEnumerator() and the Enumerator interface. This interface, discussed in more detail in Chapter 4, provides a way to iterate over all the elements in a collection using a simple set of methods that hide the way in which the collection actually stores its elements. I could use an enumerator to list the elements of an array like this:

' Import the Collections namespace, which is needed for enumerators Imports System.Collections

' Create an enumerator

Dim en As IEnumerator = array2d.GetEnumerator

While en.MoveNext = True

Console.WriteLine("{0} ", en.Current) End While

IEnumerator only has three members; two of which are used in the preceding code. MoveNext() moves to the next element in the collection, returning false when it has moved past the end. It is initially positioned before the first element, so you need to call it once in order to move to the start. The Current property returns a reference to the current element in the collection, which is simply printed out. The Reset() method, not used here, can be used to reset the enumerator to its starting position.

Note that IEnumerator treats all collections as one-dimensional, so it isn't very useful with multidimensional arrays.

To round off this discussion of getting and setting values, the Initialize^ method provides a way to initialize every element in an array by calling the default constructor for the element type. Be aware that this only works for arrays of value types, not for reference types.

Note

C# programmers can only use this method for value types that have constructors, and value types that are native to C# do not have constructors.

0 0

Post a comment