Chapter 9

Lazy Evaluation

WHAT’S IN THIS CHAPTER?

  • Strict and non-strict evaluation
  • Laziness through function passing
  • Lazy<T>
  • How lazy can you be?

C# is a language that uses a strict evaluation strategy most of the time. The topic of evaluation strategies is a complex one that applies to the techniques of passing parameters to functions, applying operators, the order in which expressions are evaluated, and several other related subjects.

As far as function calls go, strict evaluation means that parameters are evaluated before they are passed to functions. For instance, this function call uses an expression as a parameter:

MyFunction(23 * 4);

In C#, the fact that an expression was used on the calling side is no longer visible from the inside of MyFunction. The code inside the function can only see the value that is the result of an evaluation of that expression: 92.

Strict evaluation is very common, even more so in what can be considered mainstream programming languages these days. But there is competition in the form of non-strict evaluation strategies, which many programming languages use as well. Non-strict evaluation is often called lazy evaluation because the essence of it is that expressions, or parts of expressions, are only evaluated when their results are actually needed.

To see a case where C# uses non-strict evaluation, take a look at this Boolean expression:

bool isTrue = (10 < 5) && (MyCheck());

C# has a feature called short-circuiting, which is used during the ...

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.