Eager evaluation C# with Example



Eager evaluation C# with Example

The yield keyword allows lazy-evaluation of the collection. Forcibly loading the whole collection into memory is 
called eager evaluation. 
The following code shows this: 
IEnumerable myMethod() 
{ 
for(int i=0; i <= 8675309; i++) 
{ 
yield return i; 
} 
} 
... 
// define the iterator 
var it = myMethod.Take(3); 
// force its immediate evaluation 
// list will contain 0, 1, 2 
var list = it.ToList(); 
Calling ToList, ToDictionary or ToArray will force the immediate evaluation of the enumeration, retrieving all the 
elements into a collection. 

0 Comment's

Comment Form

Submit Comment