Lazy Loading By Using C# Yield Statements

I keep forgetting about that fun little yield statement we’ve got in C#. It’s that one that lets you magically create an enumerator out of a normal method.

The other day I was feeling lazy. I had a bunch of views that all shared the same model which allowed for a bunch of different editors for different types of data. Some of them needed a list of features pulled from the database. The easy thing to do would be to just slap that feature query result onto the model, but it only needed to be used by a single view and it was an expensive query with some other nonsense happening to the list in the controller, so it was slowing down all other views unnecessarily.

I then remembered the yield statement and wondered whether it would lazy-load, hoping that my slow loading method would never be called unless the view actually used it. It worked!

static void Main(string[] args)
    Console.WriteLine("Test 1 (we're not enumerating this time)");
    var foo1 = GetFeatures();

    Console.WriteLine("Test 2 (just peeking in the enumeration)");
    var foo2 = GetFeatures();
    Console.WriteLine("First entry in list: " + foo2.First());
// this is the expensive method
static IEnumerable<string> GetFeatures()
    Console.WriteLine("GetFeatures was called");

    // just pretend this is an expensive query
    var expensiveList = new string[] { "a", "b", "c", "d" };

    //and pretend we're doing something more complex
    foreach (var item in expensiveList)
        yield return item;

And the output:

Test 1 (we’re not enumerating this time)
Test 2 (just peeking in the enumeration)
GetFeatures was called
First entry in list: a
Press any key to continue . . .

Of course, all this lazy loading nonsense could be skipped if we just built the query logic inside the model’s collection get method, but that wouldn’t be very MVCy, now, would it? I’d rather set the list in the controller.

One thought on “Lazy Loading By Using C# Yield Statements

  1. If the iterator is used to build a list then you can yield the return and the caller can decide whether he wants that result in a list, or not.

Leave a Reply

Your email address will not be published. Required fields are marked *