.NET HELP

C# ArrayList (How It Works For Developers)

Published March 6, 2024
Share:

The ArrayList class is part of the .NET Framework's collections namespace, designed to store a collection of objects. It is a non-generic collection, meaning it can hold items of any data type. This feature makes it highly flexible but less type-safe compared to generic collections. The ArrayList can contain duplicate elements and allows for dynamic resizing as a valid value is added or removed. In this article, we'll discuss the basics of ArrayList and the IronPDF Library Features.

The Basics of ArrayList

The ArrayList is essentially a non-generic collection, capable of storing a number of elements of any data type, making it a versatile choice for various programming scenarios. The ability to add elements or remove items at will without the constraints of a fixed size is one of its key features. The ArrayList adjusts its size automatically to accommodate new elements, a feature made possible through its implementation of the IList interface. This dynamic resizing is crucial for applications that require collections with a varying number of elements over their lifetime.

When you instantiate an ArrayList, you're creating a collection that can hold any object value, from integers and strings to complex custom objects. Adding elements to an ArrayList is straightforward, thanks to methods like Add, which appends an object value to the end of the collection, and Insert, which places a new item at a specified index, shifting existing elements as necessary to make room. This flexibility allows developers to manage collections more effectively, adapting to the needs of the application as it evolves.

Working with Elements

Adding elements to an ArrayList is simple and intuitive. For instance, consider a scenario where you're building a collection of various types of data. With the Add method, you can append any object to your ArrayList, from strings to integers, or even other collections. The capacity of the ArrayList is automatically increased as needed, ensuring that there's always room for new object obj elements. This automatic resizing is a significant advantage over traditional arrays, which require manual resizing or the creation of a new array to accommodate more elements.

The ArrayList also provides methods for inserting and removing elements at specific positions or int index. The Insert method allows you to add an element at a specified position, effectively enabling you to place new items precisely within the collection at any specified index. Similarly, the Remove and RemoveAt methods facilitate the deletion of items, either by specifying the object to be removed or its index within the collection. This granular control over the elements within the ArrayList makes it a powerful tool for managing dynamic data.

Creating and Adding Elements

To start using an ArrayList, you first need to create an instance of it. Then, you can add elements to the ArrayList using the Add method, which inserts an object to the end of the ArrayList.

class Program
{
// public static void main
    public static void Main()
    {
        ArrayList myArrayList = new ArrayList();
        myArrayList.Add("Hello");
        myArrayList.Add(100);
        var item = "World";
        myArrayList.Add(item);
        foreach (var obj in myArrayList)
        {
            Console.WriteLine(obj);
        }
    }
}
class Program
{
// public static void main
    public static void Main()
    {
        ArrayList myArrayList = new ArrayList();
        myArrayList.Add("Hello");
        myArrayList.Add(100);
        var item = "World";
        myArrayList.Add(item);
        foreach (var obj in myArrayList)
        {
            Console.WriteLine(obj);
        }
    }
}
Friend Class Program
' public static void main
	Public Shared Sub Main()
		Dim myArrayList As New ArrayList()
		myArrayList.Add("Hello")
		myArrayList.Add(100)
		Dim item = "World"
		myArrayList.Add(item)
		For Each obj In myArrayList
			Console.WriteLine(obj)
		Next obj
	End Sub
End Class
VB   C#

C# ArrayList (How It Works For Developers): Figure 1 - Create ArrayList Output

This example demonstrates how to create a new ArrayList and add different types of elements to it. The foreach loop then iterates through the ArrayList, printing each element.

Inserting Elements

To insert an element at a specified index, use the Insert method, noting that this is a zero-based index system.

myArrayList.Insert(1, "Inserted Item");
myArrayList.Insert(1, "Inserted Item");
myArrayList.Insert(1, "Inserted Item")
VB   C#

Removing Elements

To remove elements, the Remove and RemoveAt methods come in handy. Remove deletes the first occurrence of a specific object, while RemoveAt removes the element at the specified integer index.

myArrayList.Remove("Hello"); // Removes the first occurrence of "Hello"
myArrayList.RemoveAt(0); // Removes the element at index 0
myArrayList.Remove("Hello"); // Removes the first occurrence of "Hello"
myArrayList.RemoveAt(0); // Removes the element at index 0
myArrayList.Remove("Hello") ' Removes the first occurrence of "Hello"
myArrayList.RemoveAt(0) ' Removes the element at index 0
VB   C#

Example: Managing an ArrayList

Creating an advanced example of using ArrayList in C# involves showcasing not just the basic operations like adding or removing elements, but also more complex manipulations such as sorting, searching, and converting the ArrayList to other data structures. Put the following example in the Program.cs file to run it:

using System;
using System.Collections;
using System.Linq;
class AdvancedArrayListExample
{
    static void Main(string [] args)
    {
        // Initialize an ArrayList with some elements
        ArrayList numbers = new ArrayList() { 5, 8, 1, 3, 2 };
        // Adding elements
        numbers.Add(6); // Add an element to the end
        numbers.AddRange(new int [] { 7, 9, 0 }); // Add multiple elements from a specified collection.
        Console.WriteLine("Initial ArrayList:");
        foreach (int number in numbers)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");
        // Removing elements
        numbers.Remove(1); // Remove the element 1
        numbers.RemoveAt(0); // Remove the first element
        Console.WriteLine("After Removal:");
        foreach (int number in numbers)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");
        // Sorting
        numbers.Sort(); // Sort the ArrayList
        Console.WriteLine("Sorted ArrayList:");
        foreach (int number in numbers)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");
        // Searching
        int searchFor = 5;
        int index = numbers.IndexOf(searchFor); // Find the index of the element
        if (index != -1)
        {
            Console.WriteLine($"Element {searchFor} found at index {index}");
        }
        else
        {
            Console.WriteLine($"Element {searchFor} not found.");
        }
        Console.WriteLine("\n");
        // Converting ArrayList to Array
        int [] numbersArray = (int [])numbers.ToArray(typeof(int));
        Console.WriteLine("Converted Array:");
        foreach (int number in numbersArray)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");
        // Demonstrate LINQ with ArrayList (Requires System.Linq)
        var evenNumbers = numbers.Cast<int>().Where(n => n % 2 == 0).ToList(); // Assign values to evenNumbers from the filtered results.
        Console.WriteLine("Even Numbers:");
        evenNumbers.ForEach(n => Console.Write(n + " "));
        Console.WriteLine();
    }
}
using System;
using System.Collections;
using System.Linq;
class AdvancedArrayListExample
{
    static void Main(string [] args)
    {
        // Initialize an ArrayList with some elements
        ArrayList numbers = new ArrayList() { 5, 8, 1, 3, 2 };
        // Adding elements
        numbers.Add(6); // Add an element to the end
        numbers.AddRange(new int [] { 7, 9, 0 }); // Add multiple elements from a specified collection.
        Console.WriteLine("Initial ArrayList:");
        foreach (int number in numbers)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");
        // Removing elements
        numbers.Remove(1); // Remove the element 1
        numbers.RemoveAt(0); // Remove the first element
        Console.WriteLine("After Removal:");
        foreach (int number in numbers)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");
        // Sorting
        numbers.Sort(); // Sort the ArrayList
        Console.WriteLine("Sorted ArrayList:");
        foreach (int number in numbers)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");
        // Searching
        int searchFor = 5;
        int index = numbers.IndexOf(searchFor); // Find the index of the element
        if (index != -1)
        {
            Console.WriteLine($"Element {searchFor} found at index {index}");
        }
        else
        {
            Console.WriteLine($"Element {searchFor} not found.");
        }
        Console.WriteLine("\n");
        // Converting ArrayList to Array
        int [] numbersArray = (int [])numbers.ToArray(typeof(int));
        Console.WriteLine("Converted Array:");
        foreach (int number in numbersArray)
        {
            Console.Write(number + " ");
        }
        Console.WriteLine("\n");
        // Demonstrate LINQ with ArrayList (Requires System.Linq)
        var evenNumbers = numbers.Cast<int>().Where(n => n % 2 == 0).ToList(); // Assign values to evenNumbers from the filtered results.
        Console.WriteLine("Even Numbers:");
        evenNumbers.ForEach(n => Console.Write(n + " "));
        Console.WriteLine();
    }
}
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections
Imports System.Linq
Friend Class AdvancedArrayListExample
	Shared Sub Main(ByVal args() As String)
		' Initialize an ArrayList with some elements
		Dim numbers As New ArrayList() From { 5, 8, 1, 3, 2 }
		' Adding elements
		numbers.Add(6) ' Add an element to the end
		numbers.AddRange(New Integer () { 7, 9, 0 }) ' Add multiple elements from a specified collection.
		Console.WriteLine("Initial ArrayList:")
		For Each number As Integer In numbers
			Console.Write(number & " ")
		Next number
		Console.WriteLine(vbLf)
		' Removing elements
		numbers.Remove(1) ' Remove the element 1
		numbers.RemoveAt(0) ' Remove the first element
		Console.WriteLine("After Removal:")
		For Each number As Integer In numbers
			Console.Write(number & " ")
		Next number
		Console.WriteLine(vbLf)
		' Sorting
		numbers.Sort() ' Sort the ArrayList
		Console.WriteLine("Sorted ArrayList:")
		For Each number As Integer In numbers
			Console.Write(number & " ")
		Next number
		Console.WriteLine(vbLf)
		' Searching
		Dim searchFor As Integer = 5
		Dim index As Integer = numbers.IndexOf(searchFor) ' Find the index of the element
		If index <> -1 Then
			Console.WriteLine($"Element {searchFor} found at index {index}")
		Else
			Console.WriteLine($"Element {searchFor} not found.")
		End If
		Console.WriteLine(vbLf)
		' Converting ArrayList to Array
		Dim numbersArray() As Integer = DirectCast(numbers.ToArray(GetType(Integer)), Integer ())
		Console.WriteLine("Converted Array:")
		For Each number As Integer In numbersArray
			Console.Write(number & " ")
		Next number
		Console.WriteLine(vbLf)
		' Demonstrate LINQ with ArrayList (Requires System.Linq)
		Dim evenNumbers = numbers.Cast(Of Integer)().Where(Function(n) n Mod 2 = 0).ToList() ' Assign values to evenNumbers from the filtered results.
		Console.WriteLine("Even Numbers:")
		evenNumbers.ForEach(Sub(n) Console.Write(n & " "))
		Console.WriteLine()
	End Sub
End Class
VB   C#

This code snippet demonstrates how to:

  • Initialize an ArrayList with a set of elements.
  • Add single and multiple elements to the ArrayList.
  • Remove elements by value and by index.
  • Sort the ArrayList to order the elements.
  • Search for an element and find its index.
  • Convert the ArrayList to a standard array.
  • Use LINQ with ArrayList to filter out even numbers, showcasing how to bridge non-generic collections with LINQ's powerful query capabilities.

C# ArrayList (How It Works For Developers): Figure 2 - ArrayList Output

Introduction of IronPDF: C# PDF Library

C# ArrayList (How It Works For Developers): Figure 3 - IronPDF

IronPDF is a powerful library for C# that simplifies the complex process of PDF generation, offering a wide range of features for PDF manipulation, including the ability to generate PDFs from HTML, add text and images, secure documents, and much more.

Integrating IronPDF with ArrayList

Let's write a simple C# program that creates an ArrayList of items, and then uses IronPDF to generate a PDF document listing those items.

using IronPdf;
using System;
using System.Collections;
class pdfocde
{
    static void Main(string [] args)
    {
        IronPdf.License.LicenseKey = "License";
        // Create a new ArrayList and add some items
        ArrayList itemList = new ArrayList();
        itemList.Add("Apple");
        itemList.Add("Banana");
        itemList.Add("Cherry");
        itemList.Add("Date");
        // Initialize a new PDF document
        var Renderer = new ChromePdfRenderer();
        // Create an HTML string to hold our content
        string htmlContent = "<h1>Items List</h1><ul>";
        // Iterate over each item in the ArrayList and add it to the HTML string
        foreach (var item in itemList)
        {
            htmlContent += $"<li>{item}</li>";
        }
        htmlContent += "</ul>";
        // Convert the HTML string to a PDF document
        var PDF = Renderer.RenderHtmlAsPdf(htmlContent);
        // Save the PDF to a file
        PDF.SaveAs("e:\\ItemList.pdf");
        Console.WriteLine("PDF file 'ItemList.pdf' has been generated.");
    }
}
using IronPdf;
using System;
using System.Collections;
class pdfocde
{
    static void Main(string [] args)
    {
        IronPdf.License.LicenseKey = "License";
        // Create a new ArrayList and add some items
        ArrayList itemList = new ArrayList();
        itemList.Add("Apple");
        itemList.Add("Banana");
        itemList.Add("Cherry");
        itemList.Add("Date");
        // Initialize a new PDF document
        var Renderer = new ChromePdfRenderer();
        // Create an HTML string to hold our content
        string htmlContent = "<h1>Items List</h1><ul>";
        // Iterate over each item in the ArrayList and add it to the HTML string
        foreach (var item in itemList)
        {
            htmlContent += $"<li>{item}</li>";
        }
        htmlContent += "</ul>";
        // Convert the HTML string to a PDF document
        var PDF = Renderer.RenderHtmlAsPdf(htmlContent);
        // Save the PDF to a file
        PDF.SaveAs("e:\\ItemList.pdf");
        Console.WriteLine("PDF file 'ItemList.pdf' has been generated.");
    }
}
Imports IronPdf
Imports System
Imports System.Collections
Friend Class pdfocde
	Shared Sub Main(ByVal args() As String)
		IronPdf.License.LicenseKey = "License"
		' Create a new ArrayList and add some items
		Dim itemList As New ArrayList()
		itemList.Add("Apple")
		itemList.Add("Banana")
		itemList.Add("Cherry")
		itemList.Add("Date")
		' Initialize a new PDF document
		Dim Renderer = New ChromePdfRenderer()
		' Create an HTML string to hold our content
		Dim htmlContent As String = "<h1>Items List</h1><ul>"
		' Iterate over each item in the ArrayList and add it to the HTML string
		For Each item In itemList
			htmlContent &= $"<li>{item}</li>"
		Next item
		htmlContent &= "</ul>"
		' Convert the HTML string to a PDF document
		Dim PDF = Renderer.RenderHtmlAsPdf(htmlContent)
		' Save the PDF to a file
		PDF.SaveAs("e:\ItemList.pdf")
		Console.WriteLine("PDF file 'ItemList.pdf' has been generated.")
	End Sub
End Class
VB   C#

In this example, we start by creating an ArrayList named itemList and populating it with several string items. Next, we initialize a new instance of IronPDF's ChromePdfRenderer class, which we'll use to convert HTML content into a PDF document.

Output

Here is the output PDF generated by IronPDF:

C# ArrayList (How It Works For Developers): Figure 4 - PDF Output

Conclusion

C# ArrayList (How It Works For Developers): Figure 5 - Licensing

The ArrayList is a powerful collection offered by C# for storing a list of objects. Its ability to adjust size dynamically and store elements of any type makes it versatile for a wide range of applications. However, for type safety and better performance, generic collections are recommended. Experimenting with the ArrayList and its methods will help you understand its uses and how it can fit into your applications.

Additionally, for those interested in expanding their C# capabilities into PDF manipulation, IronPDF offers a free trial for PDF Functions in .NET to explore its features. Licenses start from $749, providing a comprehensive solution for integrating PDF functionality into .NET applications.

< PREVIOUS
Math.Round C# (How It Works For Developers)
NEXT >
C# Linter (How It Works For Developers)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,622,374 View Licenses >