Intro to Arraylists in CSharp
In this article, you’ll learn how Arraylist works in CSharp and what benefits this list brings. This is something similar to an array, but we do not need to specify the type of data that we are dealing with, and we can always add elements to the Arrayliste if we have not limited them. To work with Arraylists, we must use import System.Collections; . Arraylists store the elements assigned to them as objects. That is, We can use any objects coming from System.Object here (ie, string, double, int, etc.)
class Program { public static void Main(string[] args) { // Arraylist with undefined size ArrayList myArrayList = new ArrayList(); // Arraylist with defined size ArrayList myLittleArrayList = new ArrayList(100); // Adding Elements to an Arraylist myArrayList.Add(25); myArrayList.Add("Hello"); myArrayList.Add(23.3); myArrayList.Add(15); myArrayList.Add(12.5); // Deleting of elements of an arraylist myArrayList.Remove(15); // Deleting of elements at a specific position myArrayList.RemoveAt(0); // Count how many elements are in an arraylist Console.WriteLine(meineArrayListe.Count); double total = 0; // print out elements of an arraylist foreach (object obj in meineArrayListe) { if (obj is int || obj is double) { total += (double)obj; } else { Console.WriteLine(obj); } } Console.WriteLine(total); Console.Read(); } }
As output we get:
3
Hello
35.8
The 3 stands for the count, so we have 3 elements in our Arraylist. Hello comes from our second entry and the 35.8 result from 23.3 and 15.5. Since the 15 was deleted with Remove (15) and the 25 at the beginning was also deleted with RemoveAt (0).
So you see, we have many new possibilities with ArrayList in CSharp. For more details on the individual functions of the class I recommend the documentation.