IList<T> Interface

Namespace: System.Collections.Generic

Represents a strongly typed list of objects that can be accessed by index. Provides methods for adding, removing, and searching elements, and supports indexed access.

Remarks

The IList<T> interface is the base interface for all list types in the .NET Framework. It defines a collection of objects that can be accessed by index. The index is a zero-based integer that ranges from 0 to the number of elements in the collection.

Implementations of the IList<T> interface must provide a way to access and manipulate the elements of the list. Common operations include adding, inserting, removing, and searching for elements.

The generic `IList<T>` interface provides type safety, ensuring that you can only add objects of type `T` to the list. This helps prevent runtime errors and improves code maintainability.

Members

Properties

Name Description
Item[int index]
T
Gets or sets the element at the specified index.

Methods

Name Description
Add(T item)
int
Adds an item to the end of the IList<T>.
Clear()
void
Removes all items from the IList<T>.
Contains(T item)
bool
Determines whether an element is in the IList<T>.
IndexOf(T item)
int
Determines the index of a specific item in the IList<T>.
Insert(int index, T item)
void
Inserts an item at the specified index of the IList<T>.
Remove(T item)
bool
Removes the first occurrence of a specific item from the IList<T>.
RemoveAt(int index)
void
Removes the element at the specified index of the IList<T>.
Members inherited from System.Collections.Generic.ICollection<T>
Members inherited from System.Collections.Generic.IEnumerable<T>
Members inherited from System.Collections.IEnumerable

Example


using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a list of strings.
        IList<string> words = new List<string>();

        // Add items to the list.
        words.Add("apple");
        words.Add("banana");
        words.Add("cherry");

        // Access an element by index.
        Console.WriteLine($"{words[1]}"); // Output: banana

        // Insert an element at a specific index.
        words.Insert(1, "apricot");

        // Iterate through the list.
        Console.WriteLine("List contents:");
        foreach (string word in words)
        {
            Console.WriteLine(word);
        }

        // Remove an element.
        words.Remove("banana");

        // Check if an item exists.
        if (words.Contains("apple"))
        {
            Console.WriteLine("Apple is in the list.");
        }

        // Get the index of an item.
        int cherryIndex = words.IndexOf("cherry");
        Console.WriteLine($"Cherry is at index: {cherryIndex}");

        // Clear the list.
        words.Clear();
        Console.WriteLine($"List count after clearing: {words.Count}");
    }
}
                        

See Also