Method Defer
| Edit this page View SourceDefer<TResult>(Func<IEnumerable<TResult>>)
Creates an enumerable sequence based on an enumerable factory function.
Declaration
public static IEnumerable<TResult> Defer<TResult>(Func<IEnumerable<TResult>> enumerableFactory)
Parameters
Type | Name | Description |
---|---|---|
Func<IEnumerable<TResult>> | enumerableFactory | Enumerable factory function. |
Returns
Type | Description |
---|---|
IEnumerable<TResult> | Sequence that will invoke the enumerable factory upon iteration. |
Type Parameters
Name | Description |
---|---|
TResult | Result sequence element type. |
Remarks
enumerableFactory
is not run until the sequence returned by Defer<TResult>(Func<IEnumerable<TResult>>) is enumerated. At enumeration, enumerableFactory
is executed and the sequence returned is enumerated in a streaming manner and
values are returned similarly.
enumerableFactory
is executed each time the sequence returned by Defer<TResult>(Func<IEnumerable<TResult>>) is enumerated.
Examples
The following code example demonstrates how to defer the execution of a method that returns an enumerable using Defer
.
var count = 3;
// Use a function to create a sequence at execution time
var result = SuperEnumerable
.Defer(() => Enumerable.Range(1, count));
Console.WriteLine(
"[" +
string.Join(", ", result) +
"]");
// changing count changes the length of the sequence
// returned by the function given to Defer
count = 5;
Console.WriteLine(
"[" +
string.Join(", ", result) +
"]");
// This code produces the following output:
// [1, 2, 3]
// [1, 2, 3, 4, 5]
Exceptions
Type | Condition |
---|---|
ArgumentNullException |
|
ArgumentNullException | (Thrown lazily) The sequence |