Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Enumerable.AsEnumerable: practical reference

Enumerable.AsEnumerable: practical reference: Returns the same reference viewed through IEnumerable<T>; it neither copies, buffers, nor enumerates elements. It can also force selection of LINQ-to-Objects operators.

Version: .NET LINQ; verified on .NET 10.0.14

Syntax

source.AsEnumerable(/* overload-specific arguments */)

Returns the same reference viewed through IEnumerable; it neither copies, buffers, nor enumerates elements. It can also force selection of LINQ-to-Objects operators.

Use it to hide extra methods of a concrete collection or switch the rest of a query to Enumerable extensions.

It is neither a snapshot nor mutation protection. Source changes may remain visible, and mutation during enumeration can invalidate the iterator.

The method does not validate source: passing null returns null at run time. Nullable annotations may produce a compiler warning. The exact object type and its threading properties remain unchanged.

The complete program actually uses Enumerable.AsEnumerable; its exact expected stdout is 2.

Examples

using System;
using System.Collections.Generic;
using System.Linq;

var values = new List<int> { 1 };
var view = values.AsEnumerable();
values.Add(2);
Console.WriteLine(view.Count());

Result

2

The complete program actually uses `Enumerable.AsEnumerable`; its exact expected stdout is `2`.

Sources