CSharp - Returning IEnumerable<T>, Yielding, and Deferred Queries

Description

Returning IEnumerable<T>, Yielding, and Deferred Queries

Demo

using System;
using System.Collections.Generic;
using System.Linq;
class Program//from   w w w .  ja va 2s .c  o  m
{
    static void Main(string[] args)
    {
        string[] names = { "Python", "Java", "Javascript", "Bash", "C++", "Oracle" };
        IEnumerable<string> items = names.Where(p => p.StartsWith("J"));

        foreach (string item in items)
            Console.WriteLine(item);

    }
}

Result

The query using the Where operator is not actually performed when the line containing the query is executed.

An object is returned.

It is during the enumeration of the returned object that the Where query is actually performed.

An error that occurs in the query itself may not get detected until the time the enumeration takes place.

An Intentionally Introduced Exception

Demo

using System;  
using System.Collections.Generic;
using System.Linq;  
class Program//from w  w  w  .ja  v a  2s.co m
{
    static void Main(string[] args)
    {
        string[] names = {"Python", "Java", "Javascript", "Bash", "C++", "Oracle"};  
        Console.WriteLine("before");  
        IEnumerable<string> items = names.Where(s => Char.IsLower(s[4]));  
        Console.WriteLine("after");  
        foreach(string item in items)  
            Console.WriteLine(item);  

    }
}

Result

Notice the output of After the query.

Related Topic