Unlike Visual Basic .NET, where you can use the ReDim statement to re-dimension an array, arrays are of a fixed size in C#. There are times when you might want to use variable-length arrays in your code, however, as when the user specifies at runtime how many items an array should have, or when you're opening various unknown databases full of records. The ArrayList class lets you add or remove elements to an array at runtime, thus creating dynamic-length arrays. You can see the significant public properties of ArrayList objects in Table 6.5, and the significant public methods of these objects in Table 6.6. Table 6.5. Significant Public Properties of ArrayList Objects
Table 6.6. Significant Public Methods of ArrayList Objects
Using array lists, you can use the Add method to add new elements, and the Remove and RemoveAt methods to remove elements. You can access elements with the [] operator as you can with standard arrays. As an example, we'll create a new array list and add a few elements to it, and then loop over it with a for loop (using the Count property to determine how many elements are in the array list). The elements are displayed this way: ArrayList arrayList = new ArrayList(); arrayList.Add("Now"); arrayList.Add("is"); arrayList.Add("the"); arrayList.Add("time"); for (int loopIndex = 0; loopIndex < arrayList.Count; loopIndex++) { System.Console.Write("{0} ", arrayList[loopIndex]); } You can also loop over the elements in an array list with foreach , as you see in ch06_06.cs, Listing 6.6. Listing 6.6 Creating an Array List (ch06_06.cs)using System.Collections; public class ch06_06 { public static void Main() { ArrayList arrayList = new ArrayList(); arrayList.Add("Now"); arrayList.Add("is"); arrayList.Add("the"); arrayList.Add("time"); for (int loopIndex = 0; loopIndex < arrayList.Count; loopIndex++) { System.Console.Write("{0} ", arrayList[loopIndex]); } System.Console.WriteLine(); foreach(object text in arrayList) { System.Console.Write("{0} ", text); } } } Here's what you see when you run ch06_06: C:\>ch06_06 Now is the time Now is the time Note also that, unlike standard arrays, array lists can store data of different types: arrayList.Add("No worries."); arrayList.Add(5); |