Arrays and Parameterized Properties

Team-Fly    

 
Application Development Using Visual Basic and .NET
By Robert J. Oberg, Peter Thorsteinson, Dana L. Wyatt
Table of Contents
Chapter 4.  VB.NET Essentials, Part II


Arrays are another important data type in practical programming. In VB.NET, arrays are objects. They are a reference data type. They are based on the class System.Array and so inherit the properties and methods of this class. After examining one-dimensional arrays, we examine two higher dimensional varieties known as jagged and rectangular arrays. A jagged array is an array of arrays, and each row can have a different number of elements. In rectangular arrays, all rows have the same number of elements. Arrays are a special kind of collection, which means that the For Each loop can be used for iterating through array elements.

We conclude the section with a discussion of parameterized default properties, which provide a way to access encapsulated data in a class as a property with an array notation.

Arrays

An array is a collection of elements with the following characteristics.

  • All array elements must be of the same type. The element type of an array can be any type, including an array type. An array of arrays is referred to as a jagged array.

  • An array may have one or more dimensions. For example, a two-dimensional array can be visualized as a table of values. The number of dimensions is known as the array's rank .

  • Array elements are accessed using one or more computed integer values, each known as an index . A one-dimensional array has one index.

  • In VB.NET, an array index starts at 0, as in C, C++, C#, and Java.

  • The elements of an array are created when the array object is created. The elements are automatically destroyed when there are no longer any references to the array object.

Defining and Using Arrays

In VB.NET, an array variable is defined by including parenthesis after the variable name . The variable declared is a reference to an array object. You create the array elements and establish the upper bound(s) of the array using the New operator.

 ' defines a 1-dimensional array of integers Dim a() as Integer ' create array elements a = New Integer(9) {} 

The new array elements start out with the appropriate default values for the type (0 for Integer ). The upper bound of this array is 9, which means there are 10 elements, with an index ranging from 0 through 9.

You can indicate that you are done with the array elements by assigning the array reference to Nothing .

 a = Nothing 

The garbage collector is now ready to deallocate the array and its elements.

Upper Bounds of an Arrays Is Specified in VB.NET

It is important to note that the number in parenthesis on an array declaration is the upper bounds of the dimension. Thus, if the number in parenthesis is 9, there are actually 10 elements in that dimension!

Lower Bounds of an Array Always Begins at 0 in VB.NET

VB6 programmers should note that the lower bound of an array is always 0 in VB.NET. In VB6, both lower and upper array bounds could be specified when declaring the array.

You may declare and initialize the elements in an array with one statement, using the following syntax:

 Dim primes () As Integer = {2, 3, 5, 7, 11} 

In this example, primes references a one-dimensional array of five integers. If you want to initialize a two-dimensional array, you must define row 1, then row 2, and so on. For each row, you must define each element in the row. For example:

 Dim matrix(,) As Integer = {{1, 2, 3}, {4, 5, 6}} 

You may use the following code to print out the contents of the matrix. The UBound function is used to determine the upper bound of any specified dimension of an array.

 For i = 0 To UBound(matrix, 1)    For j = 0 To UBound(matrix, 2)       Console.Write("{0,5}", matrix(i, j))    Next    Console.WriteLine() Next 

Output from the code above would be

 1    2    3 4    5    6 

System.Array

Arrays are objects. System.Array is the abstract base class for all array types. Accordingly, you can use the properties and methods of System.Array on any array. Here are some examples, shown in the ArrayMethods example.

  • Length is a property that returns the number of elements currently in the array.

  • Sort is a static method that will sort the elements of an array.

  • BinarySearch is a static method that will search for an element in a sorted array, using a binary search algorithm.

 graphics/codeexample.gif Dim a() As Integer = {5, 2, 11, 7, 3} Array.Sort(a)  ' sorts the array Dim i As Integer For i = 0 To a.Length - 1    Console.Write("{0} ", a(i)) Next Console.WriteLine() Dim target As Integer = 5 Dim index As Integer = Array.BinarySearch(a, target) If index < 0 Then    Console.WriteLine("{0} not found", target) Else    Console.WriteLine("{0} found at {1}", target, index) End If 

Here is the output:

 graphics/codeexample.gif 2 3 5 7 11 5 found at 2 

Sample Program

The program ArrayDemo is an interactive test program for arrays. A small array is created initially, and you can create new arrays. You can populate an array either with a sequence of square numbers or with random numbers . You can sort the array, reverse the array, and perform a binary search (which assumes that the array is sorted in ascending order). You can destroy the array by assigning the array reference to Nothing .

Interfaces for System.Array

If you look at the documentation for methods of System.Array, you will see many references to various interfaces , such as IComparable . By using such interfaces, you can control the behavior of methods of System.Array . For example, if you want to sort an array of objects of a class that you define, you must implement the interface IComparable in your class so that the Sort method knows how to compare elements to carry out the sort. The .NET Framework provides an implementation of IComparable for all the primitive types. We will come back to this point after we discuss interfaces in Chapter 6.

Random-Number Generation

The ArrayDemo program contains the following code for populating an array with random integers between 0 and 100.

  Dim rand As Random = New Random()  Dim i As Integer For i = 0 To size - 1    array(i) =  rand.Next(100)  Next 

The .NET Framework provides a useful class, Random , in the System namespace that can be used for generating pseudo-random numbers for simulations.

Random Constructors

The Random class has two constructors. One constructor takes no parameters, which uses a default seed. The other constructor takes an Integer parameter named seed. The default seed is based on date and time, resulting in a different stream of random numbers each time. By specifying a seed, you can produce a deterministic stream.

Random.Next Methods

There are three overloaded Next methods that return a random Integer .

 Overridable Overloads Public Function  Next  () As Integer Overridable Overloads Public Function  Next  (_   ByVal maxValue As Integer) As Integer Overridable Overloads Public Function  Next  (_   ByVal minValue As Integer, ByVal maxValue As Integer) _   As Integer 

The first Next method returns an integer greater than or equal to zero and less than Int32.MaxValue . The second method returns an integer greater than or equal to zero and less than maxValue . The third method returns an integer greater than or equal to minValue and less than or equal to maxValue .

Random.NextDouble Method

The NextDouble method produces a random double between 0.0 and 1.0.

 Overridable Public Function NextDouble() As Double 

Jagged Arrays

You can declare an array of arrays, also known as a jagged array. Each row can have a different number of elements. You can also create the array of rows, specifying how many rows there are (each row is itself an array).

 Dim binomial()() As Integer = New Integer(rows - 1)() {} 

Next, you create the individual rows.

 binomial(i) = New Integer(i) {} 

Finally, you can assign individual array elements.

 binomial(0)(0) = 1 

The example program Pascal creates and prints Pascal's triangle using a two-dimensional jagged array. Higher dimensional jagged arrays can be created following the same principles.

Rectangular Arrays

VB.NET also permits you to define rectangular arrays, where all rows have the same number of elements. First you declare the array and create all the array elements, specifying the number of rows and columns .

 graphics/codeexample.gif Dim rows As Integer = 5 Dim columns As Integer = 5 Dim MultTable(,) As Integer = _    New Integer(rows - 1, columns - 1) {} 

Then you can assign individual array elements.

 graphics/codeexample.gif MultTable(i, j) = i * j 

The example program RectangularArray creates and prints out a multiplication table.

Higher dimensional rectangular arrays can be created following the same principles.

Arrays as Collections

The class System.Array supports the IEnumerable interface. Hence arrays can be treated as collections , a topic we will discuss in Chapter 6. This means that a For Each loop can be used to iterate through the elements of an array.

The Pascal example code mentioned above contains nested For Each loops to display the jagged array. The outer loop iterates through all the rows, and the inner loop iterates through all the elements within a row.

 graphics/codeexample.gif Dim binomial()() As Integer = New Integer(rows - 1)() {} ... Console.WriteLine(_    "Pascal triangle via nested For Each loop") Dim row() As Integer  For Each row In binomial  Dim x As Integer  For Each x In row  Console.Write("{0} ", x)    Next    Console.WriteLine() Next 

Indexing With Default Parameterized Properties

VB.NET provides various ways to help the user of a class access encapsulated data. Earlier in the chapter we saw how properties can provide access to a single piece of data associated with a class, making it appear like a public field. In this section we will see how default parameterized properties provide a similar capability for accessing a group of data items, using an array index notation. Such indexing can be provided when there is a private array or other collection.

The program TestHotel\Step3 provides an illustration. This version of the Hotel class adds the capability to make hotel reservations , and the private array m_reservations stores a list of reservations in the form of ReservationListItem structure instances. The Hotel class provides the read-only property NumberReservations for the number of reservations in this list, and it provides a default read-write property for access to the elements in this list based on an integer parameter used as an index.

 graphics/codeexample.gif ' Hotel.vb - Step 3 Imports System Public Structure ReservationListItem    Public CustomerId As Integer    Public ReservationId As Integer    Public HotelName As String    Public City As String    Public ArrivalDate As DateTime    Public DepartureDate As DateTime    Public NumberDays As Integer End Structure ... Public Class Hotel    Private m_city As String    Private m_name As String    Private m_number As Integer    Private m_rate As Decimal    Private Const MAXDAY As Integer = 366    Private m_numGuests() As Integer    Private m_nextReservation As Integer = 0    Private m_nextReservationId As Integer = 1    Private Const MAXRESERVATIONS As Integer = 100  Private m_reservations() As ReservationListItem  ...    Public ReadOnly Property NumberReservations() _     As Integer       Get          Return m_nextReservation       End Get    End Property  Default Public Property reservations(_   ByVal index As Integer) As ReservationListItem   Get   Return m_reservations(index)   End Get   Set(ByVal Value As ReservationListItem)   m_reservations(index) = Value   End Set   End Property   ..  . 

The test program TestHotel.vb illustrates reading and writing individual array elements using the index notation.

 ' Change the CustomerId of first reservation  Dim item As ReservationListItem = ritz(0)  item.CustomerId = 99  ritz(0) = item  ShowReservations(ritz) 

The Default keyword means that you can access the property using only the object reference, without having to use a fully qualified name that includes the name of the property.

 ritz.reservations(0) = item      ' fully qualified ritz(0) = item                   ' short-hand 

Default Properties Must Take a Parameter in VB.NET

In VB6 simple properties without parameters could be default. For example, controls would have Text as a default property. You could then assign a string to the textbox txtName using the code txtName = "John Smith" in place of txtName.Text = "John Smith" .

Such default simple properties are not allowed in VB.NET, because there is no special notation for assigning object references (i.e., there is no Set keyword in VB.NET). This implies that the statement txtName = means you are assigning something to the object reference txtName , not to some property of it.

However, when there is a parameter to the property, ambiguity with assigning an object reference cannot arise, because there will always be the parameter on the left hand side and not just an object reference. Thus default properties with parameters are feasible .


Team-Fly    
Top
 


Application Development Using Visual BasicR and .NET
Application Development Using Visual BasicR and .NET
ISBN: N/A
EAN: N/A
Year: 2002
Pages: 190

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net