.NET HELP

C# iList (How It Works For Developers)

Published June 6, 2024
Share:

Introduction to the IList

IList is a part of the .NET Framework's Collections namespace. It is a non-generic collection interface that provides the blueprint for a collection of objects that can be individually accessed by their index. Unlike arrays, IList allows for a dynamic number of object value elements, meaning you can add or remove elements from the collection as needed. It serves as the base interface for all non-generic lists in the .NET Framework, offering a way to manage a collection of objects in a more flexible manner than arrays. We'll learn about the IList interface and the IronPDF C# PDF Library in this tutorial.

Understanding the IList Interface

The public interface IList declaration is a fundamental part of creating custom collections in C# that adhere to the IList contract specified by the .NET Framework's Collections namespace. IList includes properties and methods that enable accessing elements in the collection, counting them, and modifying the collection by adding, inserting, or removing elements. Here are some of the key properties and methods defined in the IList interface:

  • Properties like IsFixedSize and IsReadOnly inform whether the collection is of fixed size or read-only, respectively.
  • Methods such as Add, void Insert, Remove, and RemoveAt are used for modifying elements within the collection. You can add, insert, and remove elements.
  • The IndexOf method is for locating elements, and the Item property (or indexer in C#) allows for the getting and setting of elements based on their index.

Practical Usage of Public Interface IList

To showcase how IList works, let's create a simple example. This generic version example will demonstrate how to declare an IList, add items to it, and iterate over its contents.

Creating and Modifying an IList

First, let's see how to declare an IList and add items to it:

using System;
using System.Collections;
class Program
{
    void Main(string[] args)
    {
        // Creating an IList instance
        IList myIList = new ArrayList();
        // Adding elements to the IList
        myIList.Add("Hello");
        myIList.Add(10);
        myIList.Add(new object());
        // Displaying the number of values in the IList interface using count property
        Console.WriteLine($"Number of elements: {myIList.Count}");
        // Access Elements
        foreach (var element in myIList)
        {
            Console.WriteLine(element);
        }
    }
}
using System;
using System.Collections;
class Program
{
    void Main(string[] args)
    {
        // Creating an IList instance
        IList myIList = new ArrayList();
        // Adding elements to the IList
        myIList.Add("Hello");
        myIList.Add(10);
        myIList.Add(new object());
        // Displaying the number of values in the IList interface using count property
        Console.WriteLine($"Number of elements: {myIList.Count}");
        // Access Elements
        foreach (var element in myIList)
        {
            Console.WriteLine(element);
        }
    }
}
Imports System
Imports System.Collections
Friend Class Program
	Private Sub Main(ByVal args() As String)
		' Creating an IList instance
		Dim myIList As IList = New ArrayList()
		' Adding elements to the IList
		myIList.Add("Hello")
		myIList.Add(10)
		myIList.Add(New Object())
		' Displaying the number of values in the IList interface using count property
		Console.WriteLine($"Number of elements: {myIList.Count}")
		' Access Elements
		For Each element In myIList
			Console.WriteLine(element)
		Next element
	End Sub
End Class
VB   C#

In the above example, we've created an IList instance using ArrayList, a class that implements IList. We've added a mix of different types of objects to demonstrate that an IList can hold any object. Finally, we've iterated over the collection, printing out each element.

Index-Based Access and Modification

Accessing and modifying elements by their index is a key feature of IList. The following IList example shows how you can do it:

// Accessing an element by index
object value = myIList[1];
Console.WriteLine($"Element at index 1: {value}");
// Modifying an element by index
myIList[1] = 20;
Console.WriteLine($"Modified element at index 1: {myIList[1]}");
// Accessing an element by index
object value = myIList[1];
Console.WriteLine($"Element at index 1: {value}");
// Modifying an element by index
myIList[1] = 20;
Console.WriteLine($"Modified element at index 1: {myIList[1]}");
' Accessing an element by index
Dim value As Object = myIList(1)
Console.WriteLine($"Element at index 1: {value}")
' Modifying an element by index
myIList(1) = 20
Console.WriteLine($"Modified element at index 1: {myIList(1)}")
VB   C#

Implementing Custom IList

Sometimes, you might need a tailored collection that inherits IList. This allows for more control over how elements are stored, accessed, and modified. Below is an example of a simple custom collection implementing IList:

public class CustomCollection : IList
{
    private ArrayList _innerList = new ArrayList();
    public object this[int index] { get => _innerList[index]; set => _innerList[index] = value; }
    public bool IsFixedSize => _innerList.IsFixedSize;
    public bool IsReadOnly => _innerList.IsReadOnly;
    public int Count => _innerList.Count;
    public bool IsSynchronized => _innerList.IsSynchronized;
    public object SyncRoot => _innerList.SyncRoot;
// int add
    public int Add(object value)
    {
        return _innerList.Add(value);
    }
    public void Clear()
    {
        _innerList.Clear();
    }
    public bool Contains(object value)
    {
        return _innerList.Contains(value);
    }
    public int IndexOf(object value)
    {
        return _innerList.IndexOf(value);
    }
    public void Insert(int index, object value)
    {
        _innerList.Insert(index, value);
    }
    public void Remove(object value)
    {
        _innerList.Remove(value);
    }
    public void RemoveAt(int index)
    {
        _innerList.RemoveAt(index);
    }
    public void CopyTo(Array array, int index)
    {
        _innerList.CopyTo(array, index);
    }
    public IEnumerator GetEnumerator()
    {
        return _innerList.GetEnumerator();
    }
}
public class CustomCollection : IList
{
    private ArrayList _innerList = new ArrayList();
    public object this[int index] { get => _innerList[index]; set => _innerList[index] = value; }
    public bool IsFixedSize => _innerList.IsFixedSize;
    public bool IsReadOnly => _innerList.IsReadOnly;
    public int Count => _innerList.Count;
    public bool IsSynchronized => _innerList.IsSynchronized;
    public object SyncRoot => _innerList.SyncRoot;
// int add
    public int Add(object value)
    {
        return _innerList.Add(value);
    }
    public void Clear()
    {
        _innerList.Clear();
    }
    public bool Contains(object value)
    {
        return _innerList.Contains(value);
    }
    public int IndexOf(object value)
    {
        return _innerList.IndexOf(value);
    }
    public void Insert(int index, object value)
    {
        _innerList.Insert(index, value);
    }
    public void Remove(object value)
    {
        _innerList.Remove(value);
    }
    public void RemoveAt(int index)
    {
        _innerList.RemoveAt(index);
    }
    public void CopyTo(Array array, int index)
    {
        _innerList.CopyTo(array, index);
    }
    public IEnumerator GetEnumerator()
    {
        return _innerList.GetEnumerator();
    }
}
Public Class CustomCollection
	Implements IList

	Private _innerList As New ArrayList()
	Default Public Property Item(ByVal index As Integer) As Object Implements IList.Item
		Get
			Return _innerList(index)
		End Get
		Set(ByVal value As Object)
			_innerList(index) = value
		End Set
	End Property
	Public ReadOnly Property IsFixedSize() As Boolean Implements IList.IsFixedSize
		Get
			Return _innerList.IsFixedSize
		End Get
	End Property
	Public ReadOnly Property IsReadOnly() As Boolean Implements IList.IsReadOnly
		Get
			Return _innerList.IsReadOnly
		End Get
	End Property
	Public ReadOnly Property Count() As Integer Implements System.Collections.ICollection.Count
		Get
			Return _innerList.Count
		End Get
	End Property
	Public ReadOnly Property IsSynchronized() As Boolean Implements System.Collections.ICollection.IsSynchronized
		Get
			Return _innerList.IsSynchronized
		End Get
	End Property
	Public ReadOnly Property SyncRoot() As Object Implements System.Collections.ICollection.SyncRoot
		Get
			Return _innerList.SyncRoot
		End Get
	End Property
' int add
	Public Function Add(ByVal value As Object) As Integer Implements IList.Add
		Return _innerList.Add(value)
	End Function
	Public Sub Clear() Implements IList.Clear
		_innerList.Clear()
	End Sub
	Public Function Contains(ByVal value As Object) As Boolean Implements IList.Contains
		Return _innerList.Contains(value)
	End Function
	Public Function IndexOf(ByVal value As Object) As Integer Implements IList.IndexOf
		Return _innerList.IndexOf(value)
	End Function
	Public Sub Insert(ByVal index As Integer, ByVal value As Object) Implements IList.Insert
		_innerList.Insert(index, value)
	End Sub
	Public Sub Remove(ByVal value As Object) Implements IList.Remove
		_innerList.Remove(value)
	End Sub
	Public Sub RemoveAt(ByVal index As Integer) Implements IList.RemoveAt
		_innerList.RemoveAt(index)
	End Sub
	Public Sub CopyTo(ByVal array As Array, ByVal index As Integer) Implements System.Collections.ICollection.CopyTo
		_innerList.CopyTo(array, index)
	End Sub
	Public Function GetEnumerator() As IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
		Return _innerList.GetEnumerator()
	End Function
End Class
VB   C#

This CustomCollection class encapsulates an ArrayList, a class that itself implements IList. Our CustomCollection forwards calls to the underlying ArrayList, allowing it to behave like any other collection that implements IList. This example demonstrates creating a collection that can be accessed by index, modified (items added, inserted, or removed), and iterated over, just like any built-in .NET collection that implements IList.

Advanced Operations with IList

Beyond basic add, remove, and access operations, IList allows for more complex manipulations and queries. For instance, checking if the collection contains a specific object or finding the index of an object within the collection are operations that can be essential for certain applications:

// Check if the IList contains a specific object
bool contains = myIList.Contains(10); // Assuming 10 was added previously
Console.WriteLine($"Contains 10: {contains}");
// Find the index of a specific object
int index = myIList.IndexOf(10);
Console.WriteLine($"Index of 10: {index}");
// Check if the IList contains a specific object
bool contains = myIList.Contains(10); // Assuming 10 was added previously
Console.WriteLine($"Contains 10: {contains}");
// Find the index of a specific object
int index = myIList.IndexOf(10);
Console.WriteLine($"Index of 10: {index}");
' Check if the IList contains a specific object
Dim contains As Boolean = myIList.Contains(10) ' Assuming 10 was added previously
Console.WriteLine($"Contains 10: {contains}")
' Find the index of a specific object
Dim index As Integer = myIList.IndexOf(10)
Console.WriteLine($"Index of 10: {index}")
VB   C#

These operations can be particularly useful when dealing with collections of objects where you need to determine the presence or position of specific items without iterating over the entire collection.

IronPDF: C# PDF Library

C# iList (How It Works For Developers): Figure 1 - IronPDF

IronPDF is a PDF library for .NET developers that allows for the creation and manipulation of PDF documents directly within .NET applications. It supports converting HTML to PDF documents, images, and web pages to PDF. Developers can easily add PDF functionalities to their applications with this library. IronPDF also includes features for editing, merging, and splitting PDF files, which provide comprehensive control over PDF manipulation.

Code Example

Here is a straightforward example that demonstrates generating a simple PDF document from a list of strings using IronPDF and the IList interface:

using IronPdf;
using System.Collections.Generic;
public class PDFGenerator
{
    public static void GeneratePDFFromList(IList<string> dataList)
    {
        // Initialize the HtmlToPdf renderer
        var renderer = new ChromePdfRenderer();
        // Start building HTML content from the dataList
        var htmlContent = "<h1>My Data List</h1><ul>";
        foreach (var item in dataList)
        {
            htmlContent += $"<li>{item}</li>";
        }
        htmlContent += "</ul>";
        // Convert HTML string to PDF
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
        // Save the PDF to a file
        pdfDocument.SaveAs("DataList.pdf");
    }
}
// Example usage
class Program
{
    static void Main(string[] args)
    {
        License.LicenseKey = "License-Key";
        IList<string> myDataList = new List<string> { "Apple", "Banana", "Cherry" };
        PDFGenerator.GeneratePDFFromList(myDataList);
    }
}
using IronPdf;
using System.Collections.Generic;
public class PDFGenerator
{
    public static void GeneratePDFFromList(IList<string> dataList)
    {
        // Initialize the HtmlToPdf renderer
        var renderer = new ChromePdfRenderer();
        // Start building HTML content from the dataList
        var htmlContent = "<h1>My Data List</h1><ul>";
        foreach (var item in dataList)
        {
            htmlContent += $"<li>{item}</li>";
        }
        htmlContent += "</ul>";
        // Convert HTML string to PDF
        var pdfDocument = renderer.RenderHtmlAsPdf(htmlContent);
        // Save the PDF to a file
        pdfDocument.SaveAs("DataList.pdf");
    }
}
// Example usage
class Program
{
    static void Main(string[] args)
    {
        License.LicenseKey = "License-Key";
        IList<string> myDataList = new List<string> { "Apple", "Banana", "Cherry" };
        PDFGenerator.GeneratePDFFromList(myDataList);
    }
}
Imports IronPdf
Imports System.Collections.Generic
Public Class PDFGenerator
	Public Shared Sub GeneratePDFFromList(ByVal dataList As IList(Of String))
		' Initialize the HtmlToPdf renderer
		Dim renderer = New ChromePdfRenderer()
		' Start building HTML content from the dataList
		Dim htmlContent = "<h1>My Data List</h1><ul>"
		For Each item In dataList
			htmlContent &= $"<li>{item}</li>"
		Next item
		htmlContent &= "</ul>"
		' Convert HTML string to PDF
		Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlContent)
		' Save the PDF to a file
		pdfDocument.SaveAs("DataList.pdf")
	End Sub
End Class
' Example usage
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		License.LicenseKey = "License-Key"
		Dim myDataList As IList(Of String) = New List(Of String) From {"Apple", "Banana", "Cherry"}
		PDFGenerator.GeneratePDFFromList(myDataList)
	End Sub
End Class
VB   C#

In this example, an IList<string> is used to store a collection of fruit names. The GeneratePDFFromList method then iterates over this list, building an HTML string that includes each item in an unordered list. IronPDF's ChromePdfRenderer converts this HTML content into a PDF document, which is subsequently saved to a file.

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

Conclusion

C# iList (How It Works For Developers): Figure 3 - Licensing

This beginner-friendly guide aimed to cover the basics and practical uses of IList in C#. With examples ranging from simple usage to custom implementation, it's clear that IList is a powerful tool in the C# developer's toolkit. Whether you're manipulating collections of data or building your collection types, IList offers the functionality and flexibility needed for effective software development. IronPDF offers a free trial of its PDF library for interested users, with licenses available starting from $749.

< PREVIOUS
C# Linked List (How It Works For Developers)
NEXT >
Polly Retry (How It Works For Developers)

Ready to get started? Version: 2024.12 just released

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