DekGenius.com
Team LiB   Previous Section   Next Section

Chapter 15. Arrays

Most of the examples in previous chapters have dealt with one object at a time. In many applications, however, you want to work with a collection of objects all at the same time. The simplest collection in C# is the array, the only collection type for which C# provides built-in support. The other collection types, such as stack and queue, are not part of the language; they are part of the Framework Class Library. The collection classes are covered in detail in the next chapter. In this chapter, you will learn to work with three types of arrays: one-dimensional arrays, multidimensional rectangular arrays, and multidimensional jagged arrays.

To picture a one-dimensional array, imagine a series of mailboxes, all lined up one after the other. Each mailbox can hold exactly one object (letter, box, etc.). All the mailboxes must hold the same kind of object; you declare the type of object the mailboxes will hold when you declare the array.

A multidimensional array allows you to create rows of mailboxes, one above the other. If all the rows are the same length, you have a rectangular array. If each row of mailboxes is a different length, you have a jagged array.

You can think of a multidimensional array as being like a grid of rows and columns in which each slot (mailbox) contains information. For example, each column might contain information pertinent to an employee. Each row would contain all the information for a single employee.

Most often you will deal with a two-dimensional array, but larger multidimensional arrays (3-D, 4-D, etc.) are also possible.

A jagged array is a type of multi-dimensional array in which each row can have a different number of columns. A jagged array is less of a grid and more of an array of arrays — that is, an array in which the elements are arrays. This allows you to group a few arrays of varying sizes into a single array. For example, you might have an array of ten buttons, a second array of five listboxes, and a third array of seven checkboxes. You can group all three into a jagged array of controls.

This chapter also introduces the concept of indexers, a feature of C# that makes it possible to create your own classes that can be treated like arrays.

    Team LiB   Previous Section   Next Section