CSharp - Query with Intentional Exception Deferred Until Enumeration

Description

Query with Intentional Exception Deferred Until Enumeration

Demo

using System;  
using System.Collections.Generic;
using System.Linq;  
class Program/*ww  w .j  ava 2 s  . co  m*/
{
    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);  
          }  

    }
}

Result

Note

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.

Related Topic