Is there ever a reason to not use 'yield return' when returning an IEnumerable?

Viewed 6424

Simple example - you have a method or a property that returns an IEnumerable and the caller is iterating over that in a foreach() loop. Should you always be using 'yield return' in your IEnumerable method? Is there ever a reason not to? While I understand that it may not always be necessary to, or even "better" (maybe it's a very small collection for example), is there ever a reason to actively avoid doing this?

The bit of code that got me thinking about this was a function I wrote very similar to the accepted answer in this thread - How do I loop through a date range?

5 Answers

Without reading through answers I will tell you that using yield in a WCF service will mess up your FaultException!

It took me quite some time to find out that yield was the culprit. I just needed a fast way too get som errors up n running. The proper way would of course be to include an Error object in the reply but I needed it fast. I did : throw new FaultException("No subscription with id: " + subscriptionId.ToString());

But using yield, even below the actuall throwing, caused a regular exception, network

Related