Tuesday, June 5, 2012

lazy execution of IEnumerable

Chapter 8 of C# 4.0 in a Nutshell reveals that an IEnumerable crafted from a query will feature what is known as deferred or lazy execution (not unlike an IQueryable) in that the query operation is not enacted upon construction but rather at the point at which one calls .ToList() or .ToArray() to "pop" a result off. List<T> in contrast does not have this feature and, thus, such expositions another key difference between IEnumerable and List. In the example below, all of the tests pass. Notice that we can slip an extra item into the original list an IEnumerable is made from and have the added-after-the-fact value nonetheless bias what the IEnumerable ultimately does. Not so when making a list from another list.

using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Whatever.Tests
{
   [TestClass]
   public class IEnumerableTest
   {
      [TestMethod]
      public void Test()
      {
         List<int> firstList = new List<int>() { 1, 2 };
         IEnumerable<int> query = firstList.Select(n => n * 2);
         List<int> secondList = firstList.Select(n => n * 2).ToList();
         firstList.Add(3);
         int[] firstArray = query.ToArray();
         Assert.AreEqual(firstArray.Count(), 3);
         Assert.AreEqual(firstArray[0], 2);
         Assert.AreEqual(firstArray[1], 4);
         Assert.AreEqual(firstArray[2], 6);
         int[] secondArray = secondList.ToArray();
         Assert.AreEqual(secondArray.Count(), 2);
         Assert.AreEqual(secondArray[0], 2);
         Assert.AreEqual(secondArray[1], 4);
      }
   }
}

No comments:

Post a Comment