Advanced CSharp – yield
Have you ever had a situation arise where you want to create a function that returns a collection of results and you want the results to be listed in a for each loop?
Sure you have. And I bet I know what your code looked like too:
public ArrayList CollectionFunction() { ArrayList ar = new ArrayList(); for (int i = 0; i < 10; i++) { ar.Add(i * (i + 1)); } return ar; } public void CollectionEach() { foreach (object o in CollectionFunction()) Console.Write(o.ToString()); }
But did you know there is a much easier way to write this code and, as it turns out, it’s much more efficient too.
Instead of creating an array in the CollectionFunction() we can have CSharp take care of all the details by using the yield statement in our loop and making our CollectionFunction return IEnumerable instead of the ArrayList.
Here is the modified code:
public IEnumerable CollectionFunction() { for (int i = 0; i < 10; i++) { yield return (i * (i + 1)); } } public void CollectionEach() { foreach (int i in CollectionFunction()) Console.Write(i.ToString()); }
What happens under the hood is that a class is created to implement the behavior we’ve described in the code, meaning that the computation actually occurs AS we are looping through the IEnumerable object rather than building up a list, returning it, and then looping through the results.
Other post in Advanced CSharp
- Two Interfaces. Same Method. Two meanings. - September 29th, 2008
- Readonly variables in CSharp? Really?! - October 29th, 2008
- Dispose with Using - November 10th, 2008
- Delegates in .NET - December 4th, 2008
- Using Sealed in CSharp - December 8th, 2008
- CSharp checked and unchecked - December 11th, 2008
- Advanced CSharp - unsafe mode - December 15th, 2008
- Volatile variables and CSharp threads - December 22nd, 2008
- What is the global keyword in CSharp? - December 29th, 2008
- CSharp fixed keyword - January 5th, 2009
- using - There's more there than you are using - February 2nd, 2009
- Removing Warnings from CSharp Compile Cycle - March 10th, 2009
- Just say “No!” to C# Regions? Really?! - April 16th, 2009
- C# “” better than string.Empty? - April 20th, 2009
- .Net String Pool – Not Just For The Compiler - April 22nd, 2009
- CSharp ?? Operator - May 18th, 2009
- Using VB.NET From CSharp - July 1st, 2009
- What is .NET’s Object.GetHashCode() Used For? - August 5th, 2009
- ASP.NET Substitution Control - October 22nd, 2009
- Transaction Tracking Typed Datasets Using SqlTransaction - July 20th, 2010
- CSharp's Property Shortcuts - July 17th, 2012
- && vs & and | vs ||... What's the difference? - August 21st, 2012
- Advanced CSharp - yield - November 27th, 2012
- Making values nullable - December 18th, 2012
- Stackalloc in CSharp - January 22nd, 2013
- Dispose, Finalize and SuppressFinalize - June 12th, 2013
Republished by Blog Post Promoter
Related Post
-
Rick Foster
-
Rick Foster


