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 interfacesUsing 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
, andvalues
are objects of typeSystem.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 ...
Get C# 2008 Programmer's Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.