IEnumerable return type – Use it wisely!

Generic collections are present in C# since the very beginning of this language (since .NET Framework 2.0). One of the most essential feature of generic collections is possibility of enumerating through collection elements – as they’re implementing IEnumerable interface. But let’s step aside from consuming IEnumerable results and think for a while if we are using the full power of C# language when returning an IEnumerable type?

Let’s figure out the most common scenarios in which we are returning enumerable collection. Here are usual use cases:

  • process input collection
  • retrieve data stored in database/file
  • generate some random data

Let’s focus on the first use case. Usually we are just iterating through the provided objects to transform them to different type. I cannot remember how many times I did it in the following way:

public IEnumerable<ClassB> Convert(IEnumerable<ClassA> objects)
{
    var results = new List<ClassB>();

    foreach(var obj in objects)
    {
        var newObj = ConvertToClassB(obj);
        results.Add(newObj);
    }

    return results;
}

I admit I’ve read some articles about implementing an enumerator, but it seemed unattractive for me, as those articles were advising to implement a separate class implementing IEnumerable interface (link). That never seemed to be a smart solution for me. Furtunately, last time I got enlightened by someone, that yield return instruction doesn’t have to be used only in GetEnumerator method. That was really strange for me that I didn’t kow it and now it’s so obvious for me! Going back to my example – here’s how I would now implement the Convert method:

public IEnumerable<ClassB> Convert(IEnumerable<ClassA> objects)
{
    foreach(var obj in objects)
    {
        yield return ConvertToClassB(obj);
    }
}

Leave a Reply

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