Query with Intentional Exception Deferred Until Enumeration
using System; using System.Collections.Generic; using System.Linq; class Program/*from www .j a v a 2 s .c om*/ { static void Main(string[] args) { string[] strings = { "one", "two", null, "three" }; Console.WriteLine("Before Where() is called."); IEnumerable<string> ieStrings = strings.Where(s => s.Length == 3); Console.WriteLine("After Where() is called."); foreach(string s in ieStrings) { Console.WriteLine("Processing " + s); } } }
The third element in the array of strings is a null, and we cannot call null.Length.
The execution steps over the line of code calling the query just fine.
It is not until we enumerate the sequence and specifically the third element, that the exception occurs.
We called the Where operator without exception.
It's not until we try to enumerate the third element of the sequence that an exception is thrown.