Lesson 2: Using Constants, Enums, Arrays, and Collections

Lesson 2: Using Constants, Enums, Arrays, and Collections

In this lesson, you will learn how to use the user-defined Constant and Enum types and the Array type. The lesson also describes how to implement advanced array functionality with the Collection classes.

After this lesson, you will be able to

  • Create constants and enumerations, and use them in methods

  • Describe how to create and use arrays

  • Explain what a collection is and how to use one

  • Describe how to enumerate through the members of a collection or an array

Estimated lesson time: 40 minutes

When working with objects, it is frequently necessary to organize groups of objects into some kind of structure. For example, groups of similar or dissimilar objects might need to be accessed in sequence and will require syntax to keep track of their organization. Arrays allow you to organize groups of similar objects and refer to them by an index rather than by a name. Collections are similar to arrays but implement advanced functionality and can be used to organize dissimilar groups of objects as well. Constants can have user-friendly names to represent frequently used values. Enumerations (enums) allow you to organize sets of related integral constants and use the sets to help make your application easy to read and debug.

Constants and Enumerations

You might find that you frequently use certain values in your application. Constants allow you to assign user-friendly names to these values and refer to them in code. Enumerations are user-defined sets of integral constants that correspond to a set of friendly names. Using constants and enumerations makes your code easier to read, easier to debug, and less prone to errors caused by typographical errors.

Using Constants

Constants allow you to refer to frequently used values by friendly names. The Const (const) keyword defines a constant. For example:

Visual Basic .NET

Public Const Pi As Double = 3.14159265

Visual C#

public const double Pi = 3.14159265;

Constants can be of any intrinsic or enumerated type, but they cannot be of a user-defined type or an array. As the name implies, constants have a fixed value that, once set, cannot be changed or redefined. Once a constant is defined, you can use its name in code in place of the value it represents. For example:

Visual Basic .NET

Public Const Pi as Double = 3.14159265 Public Function CalculateCircleArea(ByVal r as Double) as Double Return Pi * r ^ 2 End Function

Visual C#

public const double Pi = 3.14159265; public double CalculateCircleArea(double r) { // In C#, ^ is a binary operator and not the exponent operator return Pi * r * r; }

Like variables, constants can be of any access level. If you want your constant to be available to all users of your application or component, you can declare it with the Public (public) keyword, as shown in the preceding examples. To create a constant for use only by the class, use the Private (private) keyword. The Friend (internal) keyword specifies assembly level access, and the Protected (protected) keyword allows access by inheriting types. Access levels are discussed in greater detail in Chapter 2.

Using Enumerations

Enumerations allow you to work with sets of related constants and to associate easy-to-remember names with those sets. For example, you could declare a set of enumeration constants associated with the days of the week and then refer to them by name in your code. The following code demonstrates how to declare an enumeration:

Visual Basic .NET

Public Enum DaysOfWeek Monday = 1 Tuesday = 2 Wednesday = 3 Thursday = 4 Friday = 5 Saturday = 6 Sunday = 7 End Enum

Visual C#

public enum DaysOfWeek { Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 7 }

The default data type for enumerations is Integer (int), but it can be any of the integral numeric data types (in Visual Basic .NET: Byte, Short, Integer, and Long; and in Visual C#: byte, short, int, and long). To define an enum as a different data type, you must specify it in the declaration line. For example:

Visual Basic .NET

Public Enum DaysOfWeek As Byte ' Additional code omitted

Visual C#

public enum DaysOfWeek : byte // additional code omitted

It is not necessary to supply values for the members of your enum. If you choose not to designate specific values, the members will be assigned default values numbered sequentially starting from zero. For example:

Visual Basic .NET

Public Enum Numbers zero ' equals zero one ' equals one two ' equals two End Enum

Visual C#

public enum Numbers { zero, // equals zero one, // equals one two // equals two }

Once you define the members of your enumeration, you can use them in code. In Visual Basic .NET, enumeration members convert to the value that they represent and can be used as constants in code. For example:

Visual Basic .NET

' This uses the Numbers enum from the previous example MessageBox.Show((Numbers.two * 2).ToString()) ' Displays 4

In Visual C#, however, you must explicitly convert enums to the correct integral type to access the value they represent. For example:

Visual C#

// This uses the Numbers enum from the previous example MessageBox.Show(((int)Numbers.two * 2).ToString()); // Displays 4

Because enumerations are user-defined types, you can create methods that require enumeration members as values instead of numeric values. By requiring enum members as parameters instead of numbers, you create code that is less prone to errors from inaccurate typing. The following example uses the DaysOfWeek enum from the previous example and demonstrates how to create a method that requires an enum member as a parameter:

Visual Basic .NET

Public Sub ScheduleDayOff(ByVal day As DaysOfWeek) Select Case day Case DaysOfWeek.Monday ' Implementation code omitted Case DaysOfWeek.Tuesday ' Implementation code omitted ' Additional cases omitted End Select End Sub

Visual C#

public void ScheduleDayOff(DaysOfWeek day) { switch(day) { case DaysOfWeek.Monday: // Implementation code omitted break; case DaysOfWeek.Tuesday: // Implementation code omitted break; // Additional cases omitted } }

Arrays

Arrays are a way to manage groups of similarly typed values or objects. With arrays, you can group a series of variables and refer to them with an index. You can loop through all or part of the variables and examine or affect each in turn. You also can create arrays with multiple dimensions. Arrays in the .NET Framework have built-in functionality to facilitate many tasks.

Declaring and Initializing Arrays

Arrays can be declared and initialized in the same statement. When declaring an array in this manner, you must specify the type and number of the array elements. All arrays in Visual Basic .NET and Visual C# are zero-based meaning the index of the first element is zero and numbered sequentially. In Visual Basic .NET, you must specify the number of array elements by indicating the upper bound of the array. The upper bound is the number that specifies the index of the last element of the array. When declaring an array in Visual C#, however, you must indicate the number of array elements by specifying the number of elements in the array. Thus, the upper bound of an array in Visual C# is always one less than the number used in the declaration statement. The following example demonstrates how to declare an array of integers:

Visual Basic .NET

' This line declares and initializes an array of 33 integers, with ' indexes ranging from 0 to 32 Dim myIntegers(32) As Integer

Visual C#

// This line declares and initializes an array of 32 integers, with // indexes ranging from 0 to 31 int[] myIntegers = new int[32];

Arrays can be declared and initialized in separate steps. In Visual C#, you can declare an array with one line and dynamically allocate it in another line, as shown in the following example:

Visual C#

// This line declares the array int[] myIntegers; // This line initializes the array with 32 members myIntegers = new int[32];

You can dynamically initialize arrays in Visual Basic .NET as well, but the syntax is somewhat less flexible. If you declare an array without specifying the number of elements on one line, you must provide values for each element when initializing the array. Initial values can be provided for an array by enclosing them in braces ({}) and separating them with commas, as the following example demonstrates:

Visual Basic .NET

' This line declares the array Dim myIntegers() As Integer ' This line initializes the array to six members and sets their values myIntegers = New Integer() {0,1,2,3,4,5}

You can redefine your array to change its size at run time. In Visual C#, redefinition is as simple as reinitializing the array as follows:

Visual C#

// This line declares and initializes the array int[] myIntegers = new int[32]; // This line reinitialized the array myIntegers = new int[45];

In Visual Basic .NET, you must use the ReDim statement to change the number of elements in an array. An example follows:

Visual Basic .NET

Dim myIntegers(32) As Integer ' This line reinitializes the array ReDim myIntegers(45)

In the previous examples, any data contained within an array is lost when the array is reinitialized. There is no way to preserve data when reinitializing arrays in Visual C#. In Visual Basic .NET, you can preserve existing data when reinitializing an array by using the Preserve keyword, as shown in the following example:

Visual Basic .NET

' Declares the array and initializes it with four members Dim myIntegers() As Integer = {0,1,2,3} ' Resizes the array, but retains the data in elements 0 through 3 ReDim Preserve myIntegers(10)

When creating an array of reference types, declaring and initializing an array does not create an array filled with members of that type. Rather, it creates an array of null references that can point to that type. To fill the array with members, you must assign each variable in the array to an object, which can be either a new object or an existing object. For example:

Visual Basic .NET

' This example creates an array of Widgets, then assigns each variable ' to a Widget object Dim Widgets(10) As Widget ' Assigns Widgets(0) to a new Widget object Widgets(0) = New Widget() ' Assigns Widgets(1) to an existing Widget object Dim aWidget As New Widget() Widgets(1) = aWidget ' Loops through Widgets and assigns 2 through 10 to a new object Dim Counter As Integer For Counter = 2 to 10 Widgets(Counter) = New Widget() Next

Visual C#

// This example creates an array of Widgets, then assigns each // variable to a Widget object Widget[] Widgets = new Widget[11]; // Assigns Widgets[0] to a new Widget object Widgets[0] = new Widget(); // Assigns Widgets[1] to an existing Widget object Widget aWidget = new Widget(); Widgets[1] = aWidget; // Loops through Widgets and assigns 2 through 10 to a new object for (int Counter = 2; Counter < 11; Counter++) { Widgets[Counter] = new Widget(); }

Multidimensional Arrays

The arrays discussed thus far are linear arrays, that is, arrays with only one dimension. The .NET Framework supports two kinds of multidimensional arrays: rectangular arrays and jagged arrays. The next two sections will discuss each type of multidimensional array.

Rectangular Arrays

Rectangular arrays are arrays in which each member of each dimension is extended in each other dimension by the same length. For example, a two-dimensional array can be thought of as a table, consisting of rows and columns. In a rectangular array, all the rows have the same number of columns.

You declare a rectangular array by specifying additional dimensions at declaration. The following code demonstrates various ways to declare a multidimensional rectangular array:

Visual Basic .NET

' Declares an array of 5 by 3 members Dim intArrays(4, 2) As Integer ' Declares a two-dimensional array and sets initial values Dim intArrays2( , ) As Integer = {{1, 2, 3}, {4, 5, 6}} ' Declares a cubical array and sets initial values Dim cubeArray( , , ) As Integer = {{{7, 2}, {1, 4}}, {{3, 5}, {4, 4}}} ' Declares a complex array of 3 x 3 x 4 x 5 x 6 members Dim complexArray(2, 2, 3, 4, 5) As Integer

Visual C#

// Declares an array of 5 by 3 members int[ , ] intArrays = new int[5, 3]; // Declares a two-dimensional array and sets initial values int[ , ] intArrays2 = {{1, 2, 3}, {4, 5, 6}}; // Declares a cubical array and sets initial values int[ , , ] cubeArray = {{{7, 2}, {1, 4}}, {{3, 5}, {4, 4}}}; // Declares a complex array of 3 x 3 x 4 x 5 x 6 members int[ , , , , ] complexArray = new int[3, 3, 4, 5, 6];

Jagged Arrays

The other type of multidimensional array is the jagged array. A two-dimensional jagged array can be thought of as a table where each row can have a different number of columns. For example, consider a table where families are the rows and family members are the columns. Unless each family has the same number of members, each row will have a variable number of columns. You can use a jagged array to represent such a table.

A jagged array is really an array of arrays. To create a jagged array, you declare the array of arrays with multiple sets of parentheses or brackets, and you indicate the size of the jagged array in the first set of brackets (parentheses). The following example demonstrates how to create a simple jagged array:

Visual Basic .NET

' Declares an array of 3 arrays Dim Families(2)() As String ' Initializes the first array to 4 members and sets values Families(0) = New String() {"Smith", "Mom", "Dad", "Uncle Phil"} ' Initializes the second array to 5 members and sets values Families(1) = New String() {"Jones", "Mom", "Dad", "Suzie", _  "Little Bobby"} ' Initializes the third array to 3 members and sets values Families(2) = New String() {"Williams", "Earl", "Bob"}

Visual C#

// Declares an array of 3 arrays string[][] Families = new string[3][]; // Initializes the first array to 4 members and sets values Families[0] = new string[] {"Smith", "Mom", "Dad", "Uncle Phil"}; // Initializes the second array to 5 members and sets values Families[1] = new string[] {"Jones", "Mom", "Dad", "Suzie",  "Little Bobby"}; // Initializes the third array to 3 members and sets values Families[2] = new string[] {"Williams", "Earl", "Bob"};

Collections

Collections provide advanced functionality for managing groups of objects. A collection is a specialized class that organizes and exposes a group of objects. Like arrays, members of collections can be accessed by an index. Unlike arrays, however, collections can be resized dynamically, and members can be added and removed at run time.

NOTE
This section deals specifically with the collection types found in the System.Collections namespace. It is technically possible to create a collection class that does not display this behavior by implementing only some of the interfaces usually implemented by collection types. Interfaces and their implementation will be discussed further in Chapter 4.

Collections are useful for managing groups of items that are dynamically created at run time. For example, you might create an application that analyzes a group of Customer objects, each representing a set of data about a particular customer. By creating a collection of Customer objects, you would be able to access the objects, iterate through them, add new objects as they became available, or remove objects as they became irrelevant.

The ArrayList Class

The System.Collections.ArrayList class provides general collection functionality suitable for most purposes. This class allows you to dynamically add and remove items from a simple list. Items in the list are retrieved by accessing the item index. You can create a new instance of the ArrayList class as shown in the following example:

Visual Basic .NET

Dim myList As New System.Collections.ArrayList()

Visual C#

System.Collections.ArrayList myList = new System.Collections.ArrayList();

The Add Method

Once instantiated, you can add items to the ArrayList using the Add method, as follows:

Visual Basic .NET

Dim myWidget As New Widget() myList.Add(myWidget)

Visual C#

Widget myWidget = new Widget(); myList.Add(myWidget);

The list of objects managed by the ArrayList is a zero-based collection. Zero-based means that the first object added to the list is assigned the index zero and every subsequent object to be added is assigned to the next available index.

The Item Property Indexer

You can retrieve the item at a particular index by using the Item property. In Visual Basic .NET, the Item property is the default property for collections. Thus, you can access it without using the Item property name, allowing syntax similar to that of an array. In Visual C#, default properties are called indexers, and you must use the array-like syntax rather than specifically use the Item property name. Default properties and indexers are discussed in detail in the next lesson. The following example demonstrates how to retrieve a reference to an object in a collection. Both correct syntaxes for accessing the Item property are shown.

Visual Basic .NET

Dim myObject As Object myObject = myList(0) ' The following line is equivalent to the preceding line myObject = myList.Item(0)

Visual C#

object myObject; myObject = myList[0];

All references contained in a collection are of type Object. Thus, the Item property returns a reference to an Object regardless of the actual type of the object contained therein. If you want to obtain a reference of the same type as the object contained in the list, you must explicitly cast the reference, as follows:

Visual Basic .NET

Dim myWidget As Widget ' Assumes a collection containing several Widget objects myWidget = CType(widgetCollection(0), Widget)

Visual C#

Widget myWidget; myWidget = (Widget)widgetCollection[0];

The Remove and RemoveAt Methods

You can remove an item from a collection by using the Remove and RemoveAt methods. The Remove method requires a reference to an object contained within the collection as a parameter and removes that object from the collection. For example:

Visual Basic .NET

Dim myWidget As New Widget() Dim myList As New System.Collections.ArrayList() ' Adds the Widget to the collection myList.Add(myWidget) ' Remove the Widget from the collection myList.Remove(myWidget)

Visual C#

Widget myWidget = new Widget(); System.Collections.ArrayList myList = new System.Collections.ArrayList(); // Adds the Widget to the collection myList.Add(myWidget); // Removes the Widget from the collection myList.Remove(myWidget);

If you attempt to remove an object that is not contained by a collection, you will not receive an error, but the line will be ignored.

The RemoveAt method allows you to remove an object at a particular index. For example:

Visual Basic .NET

Dim myList As New System.Collections.ArrayList() ' Adds three widgets to the collection Dim X As Integer For X = 1 to 3 Dim aWidget As New Widget() myList.Add(aWidget) Next ' Removes the widget at index 1 myList.RemoveAt(1)

Visual C#

System.Collections.ArrayList myList = new System.Collections.ArrayList(); // Adds three widgets to the collection for (int x = 0; x < 3; x++) { Widget myWidget = new Widget(); myList.Add(myWidget); } // Removes the Widget at index 1 myList.RemoveAt(1);

Note that as items are removed from a collection, the index numbers are reassigned to occupy any available spaces. Thus, index values are not static and might not always return the same reference.

The Count Property

The Count property returns the number of items in a collection. Because the collection index is zero-based, the Count property will always return one greater than the upper bound of the array.

Other Types of Collection Classes

The System.Collections namespace contains several other collection classes that you can use to organize groups of objects. These classes provide additional or specialized functionality that is unavailable in the ArrayList class. Some of these classes are briefly summarized in Table 3.6.

Table 3-6. Members of System.Collections

Class

Description

BitArray

Manages a compact array of bits (1 and 0)

CollectionBase

Serves as a base for implementing your own collection class; provides much of the back-end functionality required for collections

Hashtable

Represents a collection of key-and-value pairs that are organized based on the hash code of the key

Queue

Manages a group of objects on a first-in, first-out basis

SortedList

Organizes a group of objects and allows you to access those objects either by index or by a key value

Stack

Manages a group of objects on a first-in, last-out basis

Enumerating the Members of an Array or a Collection

Visual Basic .NET and Visual C# provide a specialized syntax for looping through the members of an array or a collection. The For Each (foreach) statement allows you to examine each member of an array or collection in turn. The syntax is as follows:

Visual Basic .NET

Dim myArray() As Integer = {1,2,3,4,5} Dim I As Integer For Each I in myArray MessageBox.Show(I.ToString()) Next

Visual C#

int[] myArray = new int[] {1,2,3,4,5}; foreach (int I in myArray) { MessageBox.Show(I.ToString()); }

When using this syntax with collections, you must ensure that all members of the collection are of the same type as the iteration variable. If you attempt to iterate through members of a collection that cannot be assigned to the iteration variable, an InvalidCastException will be thrown. To avoid this problem when working with collections that contain different types of objects, declare the iteration variable as an Object and use the typeof operator (Visual Basic .NET) or the GetType method (Visual C#) to determine if the object is the correct type. An example follows:

Visual Basic .NET

' Assumes that myList is an ArrayList that contains Strings and ' a variety of objects of other types Dim o As Object For Each o In myList If TypeOf o Is String Then MessageBox.Show(o.ToString()) End If Next

Visual C#

// Assumes that myList is an ArrayList that contains Strings and // a variety of objects of other types foreach (object o in myList) { if (o.GetType() == typeof(string)) { MessageBox.Show(o.ToString()); } }

It is important to note that when using the For Each (foreach) syntax, the reference that the iteration variable holds to the members of the collection is read-only. Thus, you cannot use For Each (foreach) to make changes to items contained in an array or collection. If you want to loop through the members of your array or collection and make changes to those members, you should use a For Next (for) loop, as demonstrated in the following example:

Visual Basic .NET

Dim myArray() As Integer = {1,2,3,4,5} Dim x As Integer For x = 0 to myArray.GetUpperBound(0) myArray(x) += 1 MessageBox.Show(myArray(x).ToString()) Next

Visual C#

int[] myArray = new int[] {1,2,3,4,5}; for (int x = 0; x <= myArray.GetUpperBound(0); x++) { myArray[x] ++; MessageBox.Show(myArray[x].ToString()); } 

Lesson Summary

  • Constants and enumerations make your code less error prone and easier to read and maintain. They do this by substituting friendly names for frequently used values. You define a constant with the Const (const) keyword. The Enum (enum) keyword is used to declare an enumeration. Constants can be of any data type. Enumerations must be of a numeric integral type.

  • Arrays can be one-dimensional or multidimensional. Multidimensional arrays can be either rectangular or jagged. In rectangular arrays, every member of each dimension is extended into the other dimensions by the same length. In jagged arrays, individual members of one dimension can be extended into other dimensions by different lengths. In either case, the more dimensions, the more complex the array.

  • Collections allow you to manage groups of objects, which can be of the same type or of different types. There are several types of collections, and all are available in the System.Collections namespace. System.Collections.ArrayList provides the basic functionality suitable for most applications.

  • You can use the For Each (foreach) statement to iterate through the members of an array or a collection, but you cannot alter members using this statement. To loop through an array or a collection and alter the members, use the For Next (for) statement.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[.  .. ]0-316
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[. .. ]0-316
ISBN: 735619263
EAN: N/A
Year: 2003
Pages: 110

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