IList Interface

The IList interface represents a collection that is both an ICollection and an IEnumerable, and it also provides methods for indexed access to its elements.

Namespace

System.Collections

Description

The IList interface is a fundamental part of the .NET collection framework. It defines a contract for ordered collections of objects that can be accessed by their zero-based index. This interface extends the ICollection interface, inheriting properties like Count and IsSynchronized, and methods like CopyTo. It also inherits from IEnumerable, allowing you to iterate through the collection using a foreach loop.

Key features of IList include:

Common Implementations

Several classes in the .NET Framework implement the IList interface:

Key Members

The IList interface defines the following key members:

Properties

Member Description
IsFixedSize Gets a value indicating whether the IList has a fixed size.
IsReadOnly Gets a value indicating whether the IList is read-only.
Item[int index] Gets or sets the element at the specified index.

Methods

Member Description
Add(object value) Adds an object to the end of the IList.
Clear() Removes all elements from the IList.
Contains(object value) Determines whether an element is in the IList.
IndexOf(object value) Returns the zero-based index of the first occurrence of a value in the IList.
Insert(int index, object value) Inserts an element into the IList at the specified index.
Remove(object value) Removes the first occurrence of a specific object from the IList.
RemoveAt(int index) Removes the element at the specified index from the IList.

Example Usage (C#)

Here's a simple example demonstrating how to use List<string>, which implements IList<string>:


using System;
using System.Collections.Generic;

public class Example
{
    public static void Main(string[] args)
    {
        IList<string> fruits = new List<string>();

        fruits.Add("Apple");
        fruits.Add("Banana");
        fruits.Add("Orange");

        Console.WriteLine($"Number of fruits: {fruits.Count}");

        Console.WriteLine("All fruits:");
        foreach (var fruit in fruits)
        {
            Console.WriteLine($"- {fruit}");
        }

        Console.WriteLine($"Fruit at index 1: {fruits[1]}");

        fruits.Remove("Banana");
        Console.WriteLine($"\nAfter removing Banana:");
        Console.WriteLine($"Number of fruits: {fruits.Count}");

        fruits.Insert(0, "Grape");
        Console.WriteLine($"\nAfter inserting Grape at index 0:");
        foreach (var fruit in fruits)
        {
            Console.WriteLine($"- {fruit}");
        }
    }
}
        

Considerations

When working with IList:

Understanding the IList interface is crucial for effectively managing ordered collections in your .NET applications.