Students
or a list of double
s. You also encounter many places in the .NET Framework class library that require the use of arrays. But arrays have a couple of fairly serious limitations that sometimes get in your way. At such times, you’ll appreciate the extensive C# repertoire of more flexible collection classes. Although arrays have the advantage of simplicity and can have multiple dimensions, they suffer from two important limitations:
- A program must declare the size of an array when it’s created. Unlike Visual Basic, C# doesn’t let you change the size of an array after it’s defined. For example, you might not know up front how big the array needs to be.
- Inserting or removing an element in the middle of an array is wildly inefficient. You have to move around all the elements to make room. In a big array, that can be a huge, time-consuming job.
If you need a multidimensional data structure, use an array. No collection allows multiple dimensions (although you can create some elaborate data structures, such as collections of arrays or collections of collections). Arrays and collections have some characteristics in common:
- Each can contain elements of only one type. You must specify that type in your code, at compile time, and after you declare the type, it can’t change.
- As with arrays, you can access most collections with array-like syntax using square brackets to specify an index:
myList[3] = “Joe”.
- Both collections and arrays have methods and properties. Thus, to find the number of elements in the following
smallPrimeNumbers
array, you call itsLength
property:
var smallPrimeNumbers = new [] { 2, 3, 5, 7, 11, 13 };
int numElements = smallPrimeNumbers.<strong>Length</strong>; // Result is 6.
With a collection, you call its Count
property:
List<int> smallPrimes = new List<int> { 2, 3, 5, 7, 11, 13 };
// Collections have a Count property.
int numElements = smallPrimes.<strong>Count</strong>;
Check out class Array
in C# Language Help to see what other methods and properties it has (7 public properties and 36 public methods).