Skip to main content

yield return in C# 4

OK, so I've been watching pluralsight videos lately and you would not believe how much they seem to love this "yield return" in C# 4.0.  Let's take a look at it in a small implementation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var numbers = new List<int>()
            {
                1,
                5,
                10,
                15,
                20,
                25
            };

            foreach (var number in GetLargeNumbers(numbers))
            {
                Console.WriteLine(number);
            }

            Console.Read();
        }

        static IEnumerable<int> GetLargeNumbers(IEnumerable<int> numbers)
        {
            foreach (var number in numbers)
            {
                if (number > 10)
                {
                    yield return number;
                }
            }
        }
    }
}

You can see that it saves some code.  For one, I don't need to build an enumerable and then return it at the end, I can just put a yield return and C# now builds it on the fly.  It kinda violates the O in SOLID to me, but that's not what its' value is.  It's value is that it only executes the code as it's needed.  This means that the numbers in the list are being evaluated each loop in the Main method, rather than all at once and then looped through.

I could show you changes to this program to test it, but I'll leave that for you.  Instead, I'll show you the really sexy part of this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            foreach (var number in GetRandomNumbers().Take(10))
            {
                Console.WriteLine(number);
            }

            Console.Read();
        }

        static IEnumerable<int> GetRandomNumbers()
        {
            var random = new Random();
            while (true)
            {
                yield return random.Next(30);
            }
        }
    }
}

Since yield return only executes as needed, we can deal with enormously large data-sets, even infinite, by only working on small pieces of them at a time.  In the example above, I create an infinite loop, that only executes for the number of random numbers I choose to Take (in this case 10).    Try it out, notice that it doesn't stack overflow on you!  Neat stuff.  I could get to like this yield return thing.

Comments

Popular posts from this blog

Managing Developers is HARD

I've been a software dev for a long time.  I've also been running my own software company for a few years now.  This is important information because of why I do these things.  I am a sofware developer because I love learning.  I slack off when doing a job that bores me, and software development always has something new to experience which keeps me excited and interested.  Why start a software company then?  That puts me in the role of manager rather than developer.  The truth is simple.  I've worked for a lot of companies, and I don't see any of them doing a great job of managing their software development.  That's not to say none of them have done a good job, but no one out there seems to be doing a great job.

How are they different?
A lot of companies get this part right.  Software developers are different from other employees.  The distinction is important in the same way it's important to acknowledge that an insurance agent is different from a construction…

When Is Software Done?

I have some very exciting news.  A piece of software I've been working on for over 2 years is released to the general public!  This is a little exciting if it were software I'd been working on for some big company.  It's very exciting because it's software I have been working on for my company.  That's right!  My company is ready to start selling software and start making money!

I'm not gonna use this blog post to talk about my company and what it does.  You can read about that in our press release.  Instead, I'm going to talk about the software industry and the concept of done.  Because, as with everything, it's more complicated than it seems.

Software is never really done
Actually that's a misnomer.  Software can really be done.  But done is sort of a quantum state--there and not there at the same time.  First and foremost, anyone can understand that software that works is complete.  If the software's purpose is to process a credit card, if th…

How to identify a skilled programmer during an interview

How does one identify a skilled programmer?  No company that has interviewed me could tell the difference between myself and other programmers they'd interview.  The interview process is truly a game of luck in this industry--on both sides.  Both the programmer and the company are basing their actions entirely on luck.

Companies have come up with numerous methods to attempt to discern a good programmer from a bad one.  The best tricks they have include a series of math problems, algorithms, problem solving technique tests, and even obscure programming questions, some without definitive answers.  As an example: Is there an authoritative source of information on the core principles that define object oriented programming?  I've heard everywhere from 3 to 7.  In a field of research about a synthetic concept, an authoritative answer is almost impossible to obtain.

Programmers were then forced to study to the interview.  Careercup is one of my favorite sites for this.  This almost …