IEnumerable<T> Interface
Represents a generic collection of objects that can be enumerated.
Namespace
Assembly
mscorlib.dll, System.Runtime.dll
Syntax
public interface IEnumerable<out T> : IEnumerable { IEnumerator<T> GetEnumerator(); }
Remarks
The IEnumerable<T> interface is the base interface for all generic collections that can be enumerated. It provides a single method, GetEnumerator, which returns an enumerator for the collection. The enumerator allows you to iterate through the collection and access its elements.
The out keyword in the generic type parameter T indicates that T is a contravariant type parameter. This means that you can use a type that is more general than the specified type. For example, if you have a collection of strings, you can treat it as an IEnumerable<object>.
IEnumerable<T> also derives from the non-generic IEnumerable interface. This allows non-generic collections to be used in contexts that require IEnumerable<T>, although it is generally recommended to use the generic version whenever possible for type safety.
Methods
-
IEnumerator<T> GetEnumerator()Returns an enumerator that iterates through the collection.
Implementations
The IEnumerable<T> interface is implemented by numerous collection types in the .NET Framework, including:
List<T>Dictionary<TKey, TValue>HashSet<T>- Arrays
- And many more...
Usage Example
The following C# code example demonstrates how to use IEnumerable<T> to iterate through a list of strings.
using System; using System.Collections.Generic; public class Example { public static void Main() { IEnumerable<string> names = new List<string> { "Alice", "Bob", "Charlie" }; foreach (string name in names) { Console.WriteLine($"Hello, {name}!"); } } }