List<T>
The classic problem with the Array
type is its fixed size. If you don't know in advance how many objects an array will hold, you run the risk of declaring either too small an array (and running out of room), or too large an array (and wasting memory).
Your program might be asking the user for input, or gathering input from a web site. As it finds objects (strings, books, values, etc.), you will add them to the array, but you have no idea how many objects you'll collect in any given session. The classic fixed-size array is not a good choice, as you can't predict how large an array you'll need.
The List
class is an array whose size is dynamically increased as required. Lists
provide a number of useful methods and properties for their manipulation. Table 9-3 shows some of the most important ones.
Table 9-3. List methods and properties
Method or property | Purpose |
---|---|
[a] | |
| Property to get or set the number of elements the |
| Property to get the number of elements currently in the array |
| Gets or sets the element at the specified index; this is the indexer for the |
| Public method to add an object to the |
| Public method that adds the elements of an |
| Public method that returns a read-only instance ... |
Get Programming C# 3.0, 5th Edition 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.