Skip to content

Instantly share code, notes, and snippets.

@panteamihai
Created June 12, 2018 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save panteamihai/2aabaf7a441c6a69905e04b39e7b3243 to your computer and use it in GitHub Desktop.
Save panteamihai/2aabaf7a441c6a69905e04b39e7b3243 to your computer and use it in GitHub Desktop.
Lazy evaluation in action with generators, and eager evaluation with lists (from Intro to RX)
public static void HotIsEager_ColdIsLazy_InTheEnumerableObservableDuality()
{
void ReadFirstValue(IEnumerable<int> list)
{
foreach (var i in list)
{
Console.WriteLine("Read out first value of {0}", i);
break;
}
}
IEnumerable<int> EagerEvaluation()
{
var result = new List<int>();
Console.WriteLine("About to return 1 eagerly");
result.Add(1);
//The code below is executed but not used
Console.WriteLine("About to return 2 eagerly");
result.Add(2);
return result;
}
IEnumerable<int> LazyEvaluation()
{
Console.WriteLine("About to return 1 lazily");
yield return 1;
//Execution stops here
Console.WriteLine("About to return 2 lazily");
yield return 2;
}
ReadFirstValue(EagerEvaluation());
Console.ReadLine();
ReadFirstValue(LazyEvaluation());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment