O'Reilly logo

C# 2008 Programmer's Reference by Wei-Meng Lee

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 13. Arrays and Collections

In programming, you often need to work with collections of related data. For example, you may have a list of customers and you need a way to store their email addresses. In that case, you can use an array to store the list of strings.

In .NET, there are many collection classes that you can use to represent groups of data. In addition, there are various interfaces that you can implement so that you can manipulate your own custom collection of data.

This chapter examines:

  • Declaring and initializing arrays

  • Declaring and using multidimensional arrays

  • Declaring a parameter array to allow a variable number of parameters in a function

  • Using the various System.Collections namespace interfaces

  • Using the different collection classes (such as Dictionary, Stacks, and Queue) in .NET

Arrays

An array is an indexed collection of items of the same type. To declare an array, specify the type with a pair of brackets followed by the variable name. The following statements declare three array variables of type int, string, and decimal, respectively:

int[] num;
            string[] sentences;
            decimal[] values;

Array variables are actually objects. In this example, num, sentences, and values are objects of type System.Array.

These statements simply declare the three variables as arrays; the variables are not initialized yet, and at this stage you do not know how many elements are contained within each array.

To initialize an array, use the new keyword. The following statements declare and initialize ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required