You can find the MSDN reference here.
Old Methodology
Usually a method that returns a collection consists of the following steps:- Create an empty IEnumerable set.
- Loop through some data (via a while, foreach or other construct)
- Add to the set within your loop.
- Exit the loop when some limit is reached.
- Return the set
public IEnumerable<int> GetEvenNumbers(int
maxCount)
{
//create and initialise IEnumerable container
List<int>
data = new List<int>();
int currentNum = 0;
//create and enter loop
while (true)
{
if (currentNum % 2 == 0)
{
//add the data to the IEnumerable container
data.Add(currentNum);
}
if (currentNum >= maxCount)
{
//limit has been reach so we exit loop
break;
}
}
//return the IEnumerable dataset
return data;
}
New Methodology
The new yield keywords allow you to shorten your code to only the following steps- Loop through some data.
- yield return within the loop
- yield break if a limit is reached before the loop is completed.
The yield return statement appends a value to the IEnumerable collection. The yield break statement exits any looping construct to prevent more items being added to the return set. If you omit yield break, the loop exits as it normally would.
Below is an example using the yield keyword for the process required.
public IEnumerable<int> GetEvenNumbers(int
maxCount)
{
int currentNum = 0;
//create and enter loop
while (true)
{
if (currentNum % 2 == 1)
{
//add the data to the IEnumerable container
using yield return
yield return
currentNum;
}
if (currentNum >= maxCount)
{
//limit has been reach so we exit loop using
yield break
yield break;
}
}
}
Performance
The difference between using the yield return and simply returning a set is subtle. Returning a set at the end of the method returns the entire set at once. The client must wait until the method is complete before it can use any values in the return set. Each time the yield return statement executes, the client has access to another element in the set. Essentially the set trickles back a little at a time. This can provide a gain in performance or perceived performance if you have a large set to return.Limitations
There are a few restrictions to using the yield keywords- These keywords cannot appear in blocks marked "unsafe"
- These keywords cannot appear in a method with ref or out parameters
- The yield return statement is not allowed inside a try-catch block, although it may be located inside a try-finally block.
- A yield break statement may not be located inside a finally block.
No comments:
Post a Comment