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!
And the output:
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.